next up previous contents
Next: Common Command-line Options Up: Compiling with GCC Previous: Optimization Options   Contents


Linking Object Files

You should always use g++ to link a program that contains C++ code, even if it also contains C code. If your program contains only C code, you should use gcc instead. Because this program contains both C and C++, you should use g++, like this:
% g++ -o reciprocal main.o reciprocal.o
% ./reciprocal 7
The reciprocal of 7 is 0.142857
As you can see, g++ has automatically linked in the standard C runtime library containing the implementation of printf. If you had needed to link in another library (such as a graphical user interface toolkit), you would have specified the library with the -l option. In Linux, library names almost always start with lib. For example, the Pluggable Authentication Module (PAM) library is called libpam.a.
% g++ -o reciprocal main.o reciprocal.o -lpam
The compiler automatically adds the lib prefix and the .a suffix.

As with header files, the linker looks for libraries in some standard places, including the /lib and /usr/lib directories that contain the standard system libraries. If you want the linker to search other directories as well, you should use the -L option. You can use this line to instruct the linker to look for libraries in the /usr/local/lib/pam directory before looking in the usual places:

% g++ -o reciprocal main.o reciprocal.o -L/usr/local/lib/pam -lpam
Although you don't have to use the -I option to get the preprocessor to search the current directory, you do have to use the -L option to get the linker to search the current directory. In particular, you could use the following to instruct the linker to find the test library in the current directory:
% gcc -o app app.o -L. -ltest
By default, gcc uses shared libraries, so if you must link against static libraries, you have to use the -static option. This means that only static libraries will be used. The following example creates an executable linked against the static ncurses.
% gcc cursesapp.c -lncurses -static

next up previous contents
Next: Common Command-line Options Up: Compiling with GCC Previous: Optimization Options   Contents
Cem Ozdogan 2007-05-16