next up previous contents
Next: Running Up: Linking Previous: Linker Options   Contents

Example Linking Zoo Program

The simplest way to link our trivial Zoo program is:-

g++ -o Zoo.exe Animal.cpp Dog.cpp Human.cpp Pig.cpp Zoo.cc

Here we have combined compilation and linking into a single command. It works because g++ (and gcc and g77) are really front-ends to both the compiler and linker and look at the file extensions to decide what to do. By removing the -c switch we have told g++ not to stop at the end of the compile stage, while the -o gets the executable called Zoo.exe that can now be executed:-

>./Zoo.exe
dog says woof woof!
pig says oink oink!
human says Hi, my name is Joe!

For programs of any significant size, its best to separate compilation and linking. First compile and build libraries, and then link using the libraries, so another way to build the program would be:-

g++ -g -c Animal.cpp
g++ -g -c Dog.cpp
g++ -g -c Human.cpp
g++ -g -c Pig.cpp
ar r libZoo.a *.o
g++ -g -o Zoo.exe Zoo.cc libZoo.a

Now when we build Zoo.exe we just compile the main program and link the remainder of the code is from a library. Alternatively, those last two steps could be:-

g++ -g -shared -o libZoo.so *.o
g++ -g -o Zoo.exe Zoo.cc libZoo.so

to use Dynamic libraries.

To make use of the linker -l and -L options, on my machine I could write:-

g++ -g -o Zoo.exe Zoo.cc -L/home/west/demo/libs -lZoo


next up previous contents
Next: Running Up: Linking Previous: Linker Options   Contents
P.D. Gronbech (IT Staff) 2015-10-02