| An Introduction to GCC - for the GNU compilers gcc and g++ by Brian J. Gough, foreword by Richard M. Stallman Paperback (6"x9"), 144 pages ISBN 0954161793 RRP £12.95 ($19.95) "An excellent introduction... fills a much-needed niche in the marketplace" --- Association of C and C++ Users book review (Issue 16-4, August 2004) Get a printed copy>>> |
2.5 Recompiling and relinking
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’.(3)
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.
| ISBN 0954161793 | An Introduction to GCC - for the GNU compilers gcc and g++ | See the print edition |