Prev | Current Page 1406 | Next

Christopher Negus

"Linux Bible, 2008 Edition: Boot up to Ubuntu, Fedora, KNOPPIX, Debian, openSUSE, and 11 Other Distributions"

As an alternative, you can use gcc??™s -c option on each file individually, which creates
object files from each file. Then in a second step, you link the object files together to create an
executable. Thus, the single command just shown becomes:
$ gcc -c file1.c
$ gcc -c file2.c
$ gcc -c file3.c
$ gcc file1.o file2.o file3.o -o progname
782
Programming in Linux Part VI
One reason to do this is to avoid recompiling files that haven??™t changed. If you change the source
code only in file3.c, for example, you don??™t need to recompile file1.c and file2.c to recreate
progname. Another reason to compile source code files individually before linking them to
create the executable is to avoid long-running compilation. Compiling multiple files in a single
gcc invocation can take a while if one of the source code modules is really lengthy.
Let??™s take a look at an example that creates a single binary executable from multiple source code
files. The example program named newhello comprises a C source code file, main.c (see
Listing 29-1); a header file, msg.h (see Listing 29-2); and another C source code file, msg.c
(see Listing 29-3).
LISTING 29-1
Main Program for newhello
/*
* main.c driver program
*/
#include
#include "msg.h"
int main(int argc, char *argv[])
{
char msg_hi[] = { "Hi there, programmer!" };
char msg_bye[] = { "Goodbye, programmer!" };
printf("%s\n", msg_hi);
prmsg(msg_bye);
return 0;
}
LISTING 29-2
Header file for newhello Helper Function
/*
* msg.


Pages:
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418