Node:Compiling multiple files, Next:Writing a makefile, Previous:Environment variables, Up:Putting a program together
It is usually very simple to compile a program that has been divided
across multiple source files. Instead of typing
gcc -o executable sourcefile.c
you would type
gcc -o executable sourcefile_1.c sourcefile_2.c ... sourcefile_n.c
For example, if you were building a simple database program called mydb
,
the command line might look something like this:
gcc -o mydb main.c keyboard_io.c db_access.c sorting.c
Of course, if (say) db_access.c
were lengthy, it might take a
long time to compile your program every time you executed this command,
even if you only made a small change in one of the other files. To
avoid this, you might want to compile each of the source files into its
own object file, then link them together to make your program. If you
did, each time you made a small change in one file, you need only
recompile that single file and then link the object files together
again, potentially a great savings in time and patience. Here is how to
generate a permanent object file for db_access.c
.
gcc -c db_access.c
This would generate a permanent object code file called
db_access.o
, indicated by the suffix .o
. You would
perform this step when needed for each of the source code files, then
link them together with the following command line:
gcc -o mydb main.o keyboard_io.o db_access.o sorting.o
You might even put the various commands into a shell file, so that you
wouldn't need to type them repeatedly. For example, you could put the
last command line into a shell file called build
, so that all you
would need to do to build your executable from object code files is type
the following line.
./build
For programs on a very small scale, this approach works quite well. If
your project grows even slightly complex, however, you will have a hard
time keeping track of which object files are "fresh" and which need to
be recreated because the corresponding source files have been changed
since their last compilation. That's where the GNU utility make
comes in. (See Writing a makefile.)