转自:http://blog.sina.com.cn/s/blog_46d528490100l0n3.html
许多情况下,头文件和源文件会单独存放在不同的目录中。
可以直接在.c文件中利用#include“/path/file.h", 通过指定头文件的路径(可以是绝对路径, 也可以是相对路径)来包含头文件. 但这明显降低了程序的可移植性. 在别的系统环境下编译可能会出现问题.
$ C_INCLUDE_PATH=/opt/gdbm-1.8.3/include
$ export C_INCLUDE_PATH
$ LIBRART_PATH=/opt/gdbm-1.8.3/lib
$ export LIBRART_PATH
可一次指定多个搜索路径,":"用于分隔它们,"."表示当前路径,如:
$ C_INCLUDE_PATH=.:/opt/gdbm-1.8.3/include:/net/include
$ LIBRARY_PATH=.:/opt/gdbm-1.8.3/lib:/net/lib
(可以添加多个路径,路径之间用:相隔,.代表当前目录,若.在最前头,也可省略)
当然,若想永久地添加这些路径,可以在.bash_profile中添加上述语句.
例如,假设存放源文件的子目录名为./src,而包含文件则放在同层次的其他目录下,如./inc。当我们在./src 目录下进行编译工作时,如何告诉GCC到哪里找头文件呢?方法如下所示:
$ gcc test.c
the -c option says not to run the linker.Then the output consists of object files output
by the assembler.
-c
The ultimate output is in the form of an object file for each source file.
.c, .i, .s, etc., with .o.
-S
an assembler code file for each nonassembler input file specified.
.c, .i, etc., with .s.
-E
in the form of preprocessed source code,which is sent to the standard output.
-v
Also print the version number of the compiler driver program and of the preprocessor
and the compiler proper.
--version Display the version number and copyrights of the invoked GCC.
-### Like -v except the commands are not executed and all command arguments are quoted.
This is useful for shell scripts to capture the driver-generated command lines.
-pipe Use pipes rather than temporary files for communication between the various
stages of compilation.
This fails to work on some systems where the assembler is unable to read from a pipe;
but the GNU assembler has no trouble.
优化选项: Options That Control Optimization(略)
关于编译选项的次序: Order does matter when you use several
Overall Options
C Language Options
下面的是一个调用数学库 libm.a 中 sin 函数的的例子,创建文件calc.c:
#include <math.h>
#include <stdio.h>
int main (void){
}
尝试单独从该文件生成一个可执行文件将导致一个链接阶段的错误:函数 sin,未在本程序中定义也不在默认库‘libc.a’中;
为避免在命令行中指定长长的路径,编译器为链接函数库提供了快捷的选项‘-l’。例如,下面的命令
$ gcc -Wall calc.c -lm -o calc
与我们上面指定库全路径‘/usr/lib/libm.a’的命令等价。
程序通常要使用很多 -l 选项来指定要链接的数学库,图形库,网络库等。
1)在实现共享库时,要将源文件编译为相对地址编码的格式。
2)Gcc选项 -fpic是实现1)中要求的选项。pic是position independent code的缩写。如:gcc -c -fpic component1.c component2.c
3)在链接时定位共享库:用-L指定绝对路径,也可以是用-l指定相对路径。
4) 在运行时,应用程序的搜索路径包括:环境变量LD_LIBRARY_PATH指定的路径、/etc/ld.so.cache中的共享库(由 ldconfig生成)、/lib和/usr/lib。另外还有一个环境变量LD_PRELOAD,在这里定义的共享库会比任何前述路径优先搜索。
gdb调试时:查看数据