To show how source files can be compiled independently we will edit
the main program main.c and modify it to print a
greeting to everyone
instead of world
:
#include "hello.h" int main (void) { hello ("everyone"); /* changed from "world" */ return 0; }
The updated file main.c can now be recompiled with the following command:
$ gcc -Wall -c main.c
This produces a new object file main.o. There is no need to create a new object file for hello_fn.c, since that file and the related files that it depends on, such as header files, have not changed.
The new object file can be relinked with the hello
function to
create a new executable file:
$ gcc main.o hello_fn.o -o hello
The resulting executable hello now uses the new main
function to produce the following output:
$ ./hello Hello, everyone!
Note that only the file main.c has been recompiled, and then
relinked with the existing object file for the hello
function.
If the file hello_fn.c had been modified instead, we could have
recompiled hello_fn.c to create a new object file
hello_fn.o and relinked this with the existing file
main.o.1
In a large project with many source files, recompiling only those that
have been modified can make a significant saving. The process of
recompiling only the modified files in a project can be automated with
the standard Unix program make
.
[1] If the prototype of a function has changed, it is necessary to modify and recompile all of the other source files which use it.