c++ - 使用 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 有什么问题?
解决方案
您没有在 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
推荐阅读
- logic-programming - 为什么析取 ASP 程序不能在答案中返回两个析取谓词实例?
- java - 无法通过 SQL Developer 连接到 Oracle Cloud 实例
- flutter - Flutter:直到卡片列表样式的一侧
- javascript - 如何在不清除所有其他矩形的情况下清除播放器的帧
- ruby-on-rails - 我无法使用 'bundle exec rspec' 执行 rspec
- python - 使用漂亮的汤从网页中的链接中抓取数据。Python
- python - 有没有办法设置 spacy 的 POS 标记?
- python - 根据列表中的匹配值在 pyspark 数据框中添加一个新列
- python - 创建时间序列堆叠条形图时出现问题,该条形图描述事件在一个月内发生的次数
- python - 如何使用osmnx生成考虑到路边和线数的道路网格?