2.4.2 Creating executables from object files
The final step in creating an executable file is to use gcc
to
link the object files together and fill in the missing addresses of
external functions. To link object files together, they are simply
listed on the command line:
$ gcc main.o hello_fn.o -o hello
This is one of the few occasions where there is no need to use the
-Wall
warning option, since the individual source files have
already been successfully compiled to object code. Once the source
files have been compiled, linking is an unambiguous process which
either succeeds or fails (it fails only if there are references which
cannot be resolved).
To perform the linking step gcc
uses the linker ld
, which
is a separate program. On GNU systems the GNU linker, GNU ld
, is
used. Other systems may use the GNU linker with GCC, or may have their
own linkers. The linker itself will be discussed later (see section 11 How the compiler works). By running the linker, gcc
creates an
executable file from the object files.
The resulting executable file can now be run:
$ ./hello
Hello, world!
It produces the same output as the version of the program using a single
source file in the previous section.