@1
The name of the C compiler is gcc. To compile a C source file, you use the -c
option. So, for example, entering this at the command prompt compiles the main.c
source file:
% gcc -c main.c
The resulting object file is named main.o.
The C++ compiler is called g++. Its operation is very similar to
reciprocal.cpp is accomplished by entering the following:
gcc; compiling
% g++ -c reciprocal.cpp
The -c option tells g++ to compile the program to an object file only; without it, g++
will attempt to link the program to produce an executable. After you’ve typed this
command, you’ll have an object file called reciprocal.o.
You’ll probably need a couple other options to build any reasonably large program.
The -I option is used to tell GCC where to search for header files. By default, GCC
looks in the current directory and in the directories where headers for the standard
libraries are installed. If you need to include header files from somewhere else, you’ll
need the -I option. For example, suppose that your project has one directory called
src, for source files, and another called include.You would compile reciprocal.cpp
like this to indicate that g++ should use the ../include directory in addition to find
reciprocal.hpp:
% g++ -c -I ../include reciprocal.cpp
@2
Now that you’ve compiled main.c and utilities.cpp, you’ll want to link them.You
should always use g++ to link a program that contains C++ code, even if it also con-(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.To link in
libpam.a, you use a command like this:
% 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,
which is the parallel of the -I option discussed earlier. 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
以上主要注意的两个问题就是:
1. 编译时,通过 -I 指定编译时另外查找的路径;
2. 链接时,通过-L指定链接时的查找lib的路径;