Separate compilation and linking with g++
-
To compile a C++ source code file and produce an object file (not a runnable program) you specify the "
-c
" flag to the compiler
-
Suppose there is a graphics module, implemented in a file
graphics.cpp
. It doesn’t contain a definition of main(), so it can’t produce a runnable program, but we we can compile it and produce an object file:
g++ -c graphics.c pp
compiles module graphics.cpp, producing object file graphics.o
-
Then a client program that uses the graphics module (and #includes graphics.hpp), and that defines main() can be written and also separately compiled:
g++ -c client.cpp
compiles client.cpp, producing object file client.o
-
To produce a runnable program, you need to link together all the needed object files. The C compiler can perform this linking step. At the same time, you can use the "-o" flag to give the result a different name than a.out:
g++ client.o graphics.o -o cmd
links object files, producing executable cmd
CONTENTS PREVIOUS NEXT