C.3.  Understanding the Linker

[ fromfile: linker.xml id: linker ]

Figure C.1.  The Linker's inputs and outputs

The Linker's inputs and outputs

Figure C.1 shows how the linker accepts binary files, which were generated by the compiler, and creates executable binaries as its output. The linker executable, on *nix machines, is called ld. It is run by g++ after all source files have been compiled successfully.

All these steps are performed when you run make, which prints out every command before it executes. By reading the output of make, you can see what arguments are passed to the compiler and linker. If an error occurs, it immediately follows the command-line that produced the error. Example C.4 shows the command-line options passed to g++, and attempts to show how g++ runs the linker, known as ld, and also passes some arguments to it.

Example C.4. linker-invocation.txt

    g++ -Wl,-rpath,/usr/local/qt-x11-free-3.2.3/lib           1 
        -o hw7                                                2
        .obj/address.o .obj/ca_address.o .obj/constraintgroup.o
        .obj/customer.o .obj/dataobject.o .obj/dataobjectfactory.o
        .obj/hw07-demo.o .obj/us_address.o .obj/moc_address.o 3
        .obj/moc_ca_address.o .obj/moc_customer.o .obj/moc_dataobject.o 
        .obj/moc_us_address.o  
        -L/usr/local/qt-x11-free-3.2.3/lib  -L/usr/X11R6/lib 
        -L/usr/local/utils/lib                                4
        -lutils -lqt -lXext -lX11 -lm                         5

1

Tells g++ to run the linker, and pass these options to ld.

2

Specify the output to be called hw7.

3

Link these object files into the executable.

4

Add another location for the linker to search for libraries.

5

Link this app with five more libraries: qt utils, ext, X11, and m.

<include src="linker-invocation.txt" href="linker-invocation.txt" id="invocationtxt" mode="cpp"/>


Linking entails the following:

This is the general idea. The linker resolves references to names by finding their real addresses in files and checking the addresses to see if they're valid for the type id. It's like a directory lookup service for C++ compilers.