5 Linking an object file

In the case of a program that consists only of one source code file, it may seem confusing that we need this extra step. However, all real programs consist of multiple source code files. These source code files may contain cross references to subroutines and variables among the files.

An object code file contains functions and variables that are defined in the corresponding source code file. However, all references external to this file are dangling. This is why we need this extra step. A linker takes a number of object code files, and resolve cross references amongst them.

Even with a program that only has a single source code file, there is still some linking to perform. For example, in our test program, there is an external reference to printf. printf is the name of a library subroutine. As a result, the linking step still needs to be performed.

Unless you prefer a more difficult method when there is a simpler one, use the following command to link C object code files:

gcc -g -o test test.o

This command looks almost exactly the same as the previous command. The only difference is that we are now supplying a .o file as input, and specify test as an output file.

The output file from linking is an executable file. As the name implies, you can run the program now.

Copyright © 2006-08-28 by Tak Auyeung