问题描述
我使用gcc(以g++
运行)和GNU make.我使用gcc预编译头文件precompiled.h
,创建precompiled.h.gch
; Makefile中的以下行可以做到这一点:
I use gcc (running as g++
) and GNU make.I use gcc to precompile a header file precompiled.h
, creating precompiled.h.gch
; the following line in a Makefile does it:
# MYCCFLAGS is a list of command-line parameters, e.g. -g -O2 -DNDEBUG
precompiled.h.gch: precompiled.h
g++ $(MYCCFLAGS) -c $< -o $@
一切都很好,直到我不得不使用不同的命令行参数运行g++
为止.在这种情况下,即使precompiled.h.gch
存在,也无法使用它,并且编译速度会慢得多.在gcc文档中,我已阅读到可以解决这种情况的信息,我必须创建一个名为precompiled.h.gch
的目录并放入那里的预编译头文件,每一组g++
命令行参数一个文件.
All was well until i had to run g++
with different command-line parameters.In this case, even though precompiled.h.gch
exists, it cannot be used, and the compilation will be much slower.In the gcc documentation i have read that to handle this situation,i have to make a directory called precompiled.h.gch
and putthe precompiled header files there,one file for each set of g++
command-line parameters.
所以现在我想知道如何更改我的Makefile来告诉g++
创建gch文件以这种方式.也许我可以运行g++
只是为了测试它是否可以使用任何现有文件在precompiled.h.gch
目录中,如果没有,则生成一个具有唯一文件名的新的预编译头文件.
So now i wonder how i should change my Makefile to tell g++
to createthe gch-files this way.Maybe i can run g++
just to test whether it can use any existing filein the precompiled.h.gch
directory,and if not, generate a new precompiled header with a unique file name.
gcc是否支持进行此类测试?
Does gcc have support for doing such a test?
也许我可以用另一种方式实现我想要的东西?
Maybe i can implement what i want in another way?
推荐答案
回答我自己的问题似乎很奇怪.无论如何,这里去.
It seems weird to answer my own question; anyway, here goes.
要检测是否存在合适的预编译头文件,请在头文件中添加一个故意的错误:
To detect whether a suitable precompiled header file exists, i add a deliberate error to my header file:
// precompiled.h
#include <iostream>
#include <vector>
...
#error Precompiled header file not found
之所以可行,是因为如果gcc找到了预编译的标头,它将不会读取.h
文件,也不会遇到错误.
This works because if gcc finds a precompiled header, it will not read the .h
file, and will not encounter the error.
要编译"这样的文件,请先消除错误,然后将结果放在一个临时文件中:
To "compile" such a file, i remove the error first, placing the result in a temporary file:
grep -v '#error' precompiled.h > precompiled.h.h
g++ -c -x c++ $(MYCCFLAGS) precompiled.h.h -o MORE_HACKERY
此处MORE_HACKERY不仅是纯文件名,还包含一些代码来制作具有唯一名称(mktemp
)的文件.为了清楚起见,将其省略.
Here MORE_HACKERY is not just a plain file name, but contains some code to make a file with unique name (mktemp
). It was omitted for clarity.
这篇关于使用GNU make创建几个预编译的头文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!