预编译头在msvc的项目中很常见,经常会看到类似stdafx.cpp, stdafx.h的文件,就是用于此目的,而msvc编译器是通过编译stdafx.cpp来生成预编译头文件stdafx.pch的。
一般同一项目下的stdafx.cpp是创建预编译头(/Yc),其他.cpp文件是使用预编译头(/Yu),所有.h文件不关心这个
总体流程预览
1)创建预编译头命令
2)其他文件使用这个stdafx.pch的方法
3)链接obj的注意
4)与其他编译器的区别
创建预编译头命令
$ cl.exe -c -Yc -Fpstdafx.pch -Fostdafx.obj stdafx.cpp
1)-Yc就是创建预编译头stdafx.pch
2)-Fp来指定*.pch的输出文件路径
3)-Fo指定编译stdafx.cpp生成对象文件
通过将stdafx.h传入-Yu来告诉编译器,编译当前代码,忽略#include “stdafx.h”,直接使用已经编译好的stdafx.pch文件。
cl.exe -c -Yustdafx.h -Fpstdafx.pch -Fotest.obj test.cpp
link.exe -out:test test.obj stdafx.obj
1)从stdafx.h所在目录中,查找stdafx.h.pch文件是否存在
2)从-I的头文件搜索路径找查找stdafx.h.pch
1)编译头文件生成pch文件:
2)使用预编译头文件:
gcc -c -o stdafx.pch stdafx.h
gcc -c -include stdafx.h -o test.o test.cpp
1)gcc、clang对于*.h的头文件编译,默认是作为c预编译头来使用的,这跟c++的pch是不一样的。
2)*.h的头文件编译无法给c++的代码使用,如果要生成c++可用的pch文件,必须要告诉编译器,如何去编译stdafx.h
gcc -c -x c++-header -o stdafx.pch stdafx.h
gcc -c -o stdafx.pch stdafx.hpp