使用 makefile 构建时 GCC 未使用预编译 headers

Precompiled headers not used by GCC when building with a makefile

我正在尝试将预编译的 headers 与 GCC 一起使用以加快编译过程。如果我直接从命令行启动编译,则会使用预编译的 header,但如果我尝试使用 makefile 组织编译,则不会。

更具体地说,我尝试用 GCC 8.1.0 编译文件 main.cpp 使用预编译的 header lib.hpp.gch 文件 lib.hpp 包含 作为第一个标记 在 main.cpp.

lib.hpp 预编译为

$ g++ -O2 -H -Wall -std=c++17 -c lib.hpp

main.cpp 然后用

编译
$ g++ -O2 -H -Wall -std=c++17 -c main.cpp -o main.o
! lib.hpp.gch
...

而且我可以从“!”中看出实际使用预编译的 lib.hpp.gch。

如果我为此编写一个 makefile

CXX = g++
CXXFLAGS = -O2 -H -Wall -std=c++17

main.o: \
    main.cpp \
    main.hpp \
    lib.hpp
    $(CXX) $(CXXFLAGS) \
    -c main.cpp \
    -o main.o

然后使用make,我希望预编译的用法相同header

但它失败了,从 "x":

可以看出
$ make
g++ -O2 -H -Wall -std=c++17 \
    -c main.cpp \
    -o main.o
x lib.hpp.gch
...

这很奇怪,因为make发出的命令和我之前手动使用的命令好像一模一样

我也测量了时间,可以确认通过 make 编译肯定比手动编译慢,确认未使用预编译 header。

makefile 有什么问题?

您没有在 make 命令中的任何位置包含 PCH。试试这个:

CXX = g++
CXXFLAGS = -O2 -H -Wall -std=c++17
OBJ = main.o #more objects here eventually I would think!

PCH_SRC = lib.hpp
PCH_HEADERS = headersthataregoinginyourpch.hpp andanother.hpp
PCH_OUT = lib.hpp.gch

main: $(OBJ) 
     $(CXX) $(CXXFLAGS) -o $@ $^

# Compiles your PCH
$(PCH_OUT): $(PCH_SRC) $(PCH_HEADERS)
     $(CXX) $(CXXFLAGS) -o $@ $<

# the -include flag instructs the compiler to act as if lib.hpp
# were the first header in every source file
%.o: %.cpp $(PCH_OUT)
    $(CXX) $(CXXFLAGS) -include $(PCH_SRC) -c -o $@ $<

首先编译PCH。然后所有 cpp 命令都用 -include lib.hpp 编译,这保证 lib.hpp.gch 总是先被搜索 before lib.hpp