用GCC预编译的头文件
任何人都可以使用GCC预编译头文件取得成功吗?我的尝试没有运气,也没有看到很多很好的例子来设置它。我试过cygwin gcc 3.4.4,并在Ubuntu上使用4.0。
解决方案
回答
过去,我已经设法使预编译的头文件在gcc下工作,并且我还记得当时也遇到了问题。要记住的是,如果不满足某些条件,gcc将忽略该文件(header.h.gch或者类似文件),可以在gcc预编译的头文件说明页上找到该文件的列表。
通常,最安全的做法是让构建系统首先编译.gch文件,并使用与其他源代码相同的命令行选项和可执行文件。这样可以确保文件是最新的,并且没有细微的差异。
首先将其与人为设计的示例一起使用可能也是一个好主意,只是消除了问题特定于项目中的源代码的可能性。
回答
调用gcc的方式与调用源文件的方式相同,但带有头文件。
例如
g++ $(CPPFLAGS) test.h
这将生成一个名为test.h.gch的文件
每次gcc搜索test.h时,它都会首先查找test.h.gch,如果找到它,它将自动使用它。
可以在GCC预编译标题下找到更多信息
回答
首先,请参阅此处的文档。
我们可以像其他任何文件一样编译标头,但是将输出放在带有后缀.gch的文件中。
因此,例如,如果我们预编译stdafx.h,则将具有一个预编译的头文件,只要我们包含stdafx.h
,它就会自动搜索名为stdafx.h.gch
的文件。
例子:
stdafx.h:
#include <string> #include <stdio.h>
a.cpp:
#include "stdafx.h" int main(int argc, char**argv) { std::string s = "Hi"; return 0; }
然后编译为:
> g++ -c stdafx.h -o stdafx.h.gch > g++ a.cpp > ./a.out
即使在步骤1之后删除了stdafx.h,编译也将起作用。
回答
我绝对有成功。首先,我使用以下代码:
#include <boost/xpressive/xpressive.hpp> #include <iostream> using namespace std; using namespace boost::xpressive; //A simple regex test int main() { std::string hello( "hello world!" ); sregex rex = sregex::compile( "(\w+) (\w+)!" ); smatch what; if( regex_match( hello, what, rex ) ) { std::cout << what[0] << '\n'; // whole match std::cout << what[1] << '\n'; // first capture std::cout << what[2] << '\n'; // second capture } return 0; }
这只是Boost Xpressive的一个问候世界(请参阅下面的链接)。首先,我在gcc中使用了-H选项进行编译。它显示了它使用的大量头文件列表。然后,我查看了我的IDE(code :: blocks)正在生成的编译标志,并看到了类似的内容:
g ++ -Wall -fexceptions -g -c main.cpp -o obj / Debug / main.o`
所以我写了一个命令,用完全相同的标志编译Xpressive.hpp文件:
sudo g ++ -Wall -fexceptions -g / usr / local / include / boost / xpressive / xpressive.hpp
我再次用-H编译了原始代码,并得到以下输出:
g++ -Wall -fexceptions -H -g -c main.cpp -o obj/Debug/main.o ! /usr/local/include/boost/xpressive/xpressive.hpp.gch main.cpp . /usr/include/c++/4.4/iostream .. /usr/include/c++/4.4/x86_64-linux-gnu/bits/c++config.h .. /usr/include/c++/4.4/ostream .. /usr/include/c++/4.4/istream main.cpp
这 !表示编译器能够使用预编译的头文件。 x表示它无法使用它。使用适当的编译器标志至关重要。我摘下-H并进行了一些速度测试。预编译的头文件从14秒提高到11秒。不错,但不是很好。
注意:以下是示例的链接:http://www.boost.org/doc/libs/1_43_0/doc/html/xpressive/user_s_guide.html#boost_xpressive.user_s_guide.examples我无法使其在邮政。
顺便说一句:我正在使用以下g ++
g ++(Ubuntu 4.4.3-4ubuntu5)4.4.3`