为了便于理解一个gcc的编译过程,将完整的代码编译过程分为以下四步(现在已经简化为一句代码就可实现这几句话),以一个test.cpp文件编译成可执行文件为例:
预处理-Pre-processing: 生成.i文件
# -E 选项 代表指示编译器仅对输入文件进行预处理
g++ -E test.cpp -o test.i
编译-Compiling: 生成.s文件
# -S 告诉C++代码产生汇编语言
# g++ 产生的汇编语言文件缺省扩展名是 _s
g++ -S test.i -o test.s
汇编-Assembling: 生成.o文件
# -c 告诉C++代码产生机器语言
# g++ 产生的机器语言的缺省扩展名是.o
g++ -c test.s -o test.o
链接-Linking: 生成.bin文件
# -o 表示为可执行文件重新命名,之前的-o都是
g++ test.o -o test
一步代码融合了上述四个步骤:
如果没有-o参数,会默认生成a.out可执行文件
g++ test.cpp -o test
同级目录下出现了test可执行文件,运行:
./test
即可执行
g++ -g test.cpp -o test
# 这样出来的程序,运行时间和文件大小都优化了,time ./test指令可以查看运行时间
g++ -O2 test.cpp -o test
g++ -lglog test.cpp -o test
g++ -L/home/home/qinsir/mylib -lmytest test.cpp -o test
g++ -I/. test.cpp -o test
g++ -Wall test.cpp -o test
用法同上
g++ -std=c++11 test.cpp -o test
gcc -DDEBUG main.cpp -o test
main.cpp文件内容:
int main()
{
#ifdef DEBUG
printf("DEBUG LOG\n");
#endif
printf("in\n") ;
}
按照上述编译,DEBUG为真,输出"DEBUG LOG"