【问题标题】:gcc precompiled headers weird behaviour with -c option使用 -c 选项的 gcc 预编译头文件的奇怪行为
【发布时间】:2010-03-27 20:44:51
【问题描述】:

短篇小说:

我无法使用 gcc -c 选项使预编译的头文件正常工作。

长篇大论:

伙计们,我在 Linux 上使用 gcc-4.4.1,在一个非常大的项目中尝试预编译头文件之前,我决定在简单的程序上测试它们。他们“有点工作”,但我对结果不满意,我确定我的设置有问题。

首先,我写了一个简单的程序(main.cpp)来测试它们是否工作:

#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/type_traits.hpp>

int main()
{
  return 0;
}

然后我创建了预编译的头文件pre.h(在同一目录中)如下:

#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/type_traits.hpp>

...并编译它:

$ g++ -I. pre.h

(pre.h.gch 已创建)

之后,我测量了使用和不使用预编译头文件的编译时间:

与 pch

$ time g++ -I. -include pre.h main.cpp

real    0m0.128s
user    0m0.088s
sys  0m0.048s

没有 pch

$ time g++ -I. main.cpp 

real    0m0.838s
user    0m0.784s
sys  0m0.056s

到目前为止一切顺利! 快了将近 7 倍,令人印象深刻!现在让我们尝试一些更真实的东西。我所有的源代码都是用 -c 选项构建的,出于某种原因,我不能让 pch 很好地使用它。您可以通过以下步骤重现此内容...

我创建了测试模块 foo.cpp 如下:

#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/type_traits.hpp>

int whatever()
{
  return 0;
}

以下是我尝试使用和不使用 pch 构建模块 foo.cpp 的时间:

与 pch

$ time g++ -I. -include pre.h -c foo.cpp 

real    0m0.357s
user    0m0.348s
sys 0m0.012s

没有 pch

$ time g++ -I. -c foo.cpp 

real    0m0.330s
user    0m0.292s
sys 0m0.044s

这很奇怪,看起来根本没有加速!(我跑了几次计时)。事实证明,在这种情况下根本没有使用预编译的头文件,我用 -H 选项检查了它(“g++ -I. -include pre.h -c foo.cpp -H”的输出没有列出 pre.h。 gch)。

我做错了什么?

【问题讨论】:

    标签: c++ gcc precompiled-headers


    【解决方案1】:

    好的,我想我已经找到了解决方案:-fpch-preprocess 应该与 -c 选项一起使用。它就像一个魅力!

    时间安排如下:

    与 pch

    $ time g++ -I. -include pre.h -c foo.cpp -fpch-preprocess
    
    real    0m0.028s
    user    0m0.016s
    sys 0m0.016s
    

    没有 pch

    $ time g++ -I. -c foo.cpp 
    
    real    0m0.330s
    user    0m0.292s
    sys 0m0.044s
    

    更新:我在 gcc 帮助邮件列表上问了同样的问题,Ian Lance Taylor 通过我使用 distcc/ccache 解释了这种奇怪的行为。这些工具首先对源进行预处理,这就是需要此选项的原因。

    【讨论】:

      猜你喜欢
      • 2017-03-29
      • 2010-09-08
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多