首页 > 解决方案 > 使用 makefile 构建时 GCC 未使用的预编译头文件

问题描述

我正在尝试使用带有 GCC 的预编译头文件来加快编译过程。如果我直接从命令行启动编译,则使用预编译的头文件,但如果我尝试使用 makefile 组织编译,则不会。

更具体地说,我尝试使用 GCC 8.1.0 编译文件main.cpp,并使用预编译头文件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,我希望预编译头文件的用法相同

但相反,它失败了,从“x”可以看出:

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

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

我还测量了时间,可以确认通过 make 编译肯定比手动编译慢,确认没有使用预编译的头文件。

makefile 有什么问题?

标签: c++gccmakefileprecompiled-headers

解决方案


您没有在 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将始终先搜索 lib.hpp


推荐阅读