gcc 编译过程
gcc 的编译过程可以划分为四个阶段:预处理(Pre-Processing)、编译(Compiling)、汇编(Assembling)、链接(Linking)。
gcc 基本语法
语法格式:
gcc [options] file...
常用选项:
选项 | 作用 |
---|---|
-E | 执行到预处理 |
-S | 执行到编译 |
-c | 执行到汇编 |
-o <文件名> | 指定输出文件的文件名 |
-I <目录名> | 指定头文件目录(将指定目录添加到头文件的搜索路径列表) |
-L <目录名> | 指定链接的库文件目录(将指定目录添加到库文件的搜索路径列表) |
-l <文件名> | 指定链接的库文件(让指定的库文件参与链接) |
-Wall | 显示警告信息 |
-g | 加入调试信息,方便 gdb 调试 |
使用示例:
gcc -E test.c -o test.i
gcc -S test.i -o test.s
gcc -c test.s -o test.o
gcc test.o -o test
gcc test.c -o test
创建和使用动态库(示例)
创建动态库:
gcc -shared hello.c -o libhello.so
使用动态库:
-
gcc test.c -lhello -L<libhello.so所在目录> -o test
或:gcc test.c libhello.so [-L <libhello.so所在目录>] -o test
-
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:<libhello.so所在目录>
或:把 libhello.so 放到 /lib 目录 -
./test
注:
- 执行
gcc test.c libhello.so [-L <libhello.so所在目录>] -o test
时,如果 libhello.so 不在当前目录下,需要指明其路径
创建和使用静态库(示例)
创建静态库:
-
gcc -c [-fPIC] hello.c -o hello.o
-
ar -crs libhello.a hello.o
使用静态库:
-
gcc test.c -lhello -L<libhello.a所在目录> -o test
或:gcc test.c libhello.a [-L <libhello.a所在目录>] -o test
-
./test
注:
-
执行
arm-linux-gnueabihf-gcc -c [-fPIC] hello.c -o hello.o
交叉编译时,需要加上 -fPIC 参数 -
执行
gcc test.c libhello.a [-L <libhello.a所在目录>] -o test
时,如果 libhello.a 不在当前目录下,需要指明其路径