编译
以上的编译可以分为以下四步
预处理(Pre-Procession)
1 2 3 4
| g++ -E source.cpp -o source.i
cpp source.cpp target.cpp
|
纯编译(Compiling)
1 2 3 4 5 6
|
g++ -S source.cpp -o preprocessed.s
cpp source.cpp preprocessed.cpp /usr/lib/gcc/x86_64-linux-gnu/9/cc1plus preprocessed.cpp
|
c++filt 这个工具来帮助我们还原混淆符号对应的函数签名
汇编(Assembling)
1 2 3 4
| g++ -c source.cpp -0 preprocessed.o
as preprocessed.s -o preprocessed.o
|
file 查看文件类型
readelf 查看elf文件信息
nm 展示文件中符号
链接(Linking)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| g++ preprocessed.o
ld -static preprocessed.o \ /usr/lib/x86_64-linux-gnu/crt1.o \ /usr/lib/x86_64-linux-gnu/crti.o \ /usr/lib/gcc/x86_64-linux-gnu/9/crtbeginT.o \ -L/usr/lib/gcc/x86_64-linux-gnu/9 \ -L/usr/lib/x86_64-linux-gnu \ -L/lib/x86_64-linux-gnu \ -L/lib \ -L/usr/lib \ -lstdc++ \ -lm \ --start-group \ -lgcc \ -lgcc_eh \ -lc \ --end-group \ /usr/lib/gcc/x86_64-linux-gnu/9/crtend.o \ /usr/lib/x86_64-linux-gnu/crtn.o
|
g++重要参数
- -g
编译带调试信息的可执行文件
- -O[n]
代码优化,可选参数
- -O 不做优化
- -O1 默认优化
- -O2 除O1外,进一步优化
- -O3 更进一步的优化
- -l/L
- -l紧跟着就是库名,
/lib,/usr/lib,/usr/local/lib里直接-l库名就能链接
- -L紧跟着就是库所在目录
1 2
| g++ -lglong test.cpp g++ -L/home/temp/mytestlibfolder -lmytest test.cpp
|
- -I
指定头文件搜索路径,/usr/include可以不需要指定
1
| g++ -I/myinclude test.cpp
|
- -Wall
打印警告信息
- -w
关闭警告信息
- -std=[n]
指定c++标准
- -D
定义宏
创建和使用链接库
假设我们有这么一个程序,它的作用是用来交换数字,目录结构如下:
1 2 3 4 5
| - include - swap.h - main.cpp - src - swap.cpp
|
静态库
1 2 3 4 5 6 7 8 9 10 11 12 13
|
cd src
g++ swap.cpp -c -I../include
ar rs libswap.a swap.o
cd ..
g++ main.cpp -Iinclude -Lsrc -lswap -o staticmain
|
动态库
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
cd src
g++ swap.cpp -I../include -fPIC -shared -o libswap.so
cd ..
g++ main.cpp -Iinclude -Lsrc -lswap -o sharemain
|
运行动态库的程序时,指定库路径
1 2
| LD_LIBRARY_PATH=src ./sharemain
|
参考
- 编译过程概览