在跨平台代码中处理stdafx.h

dim*_*mba 53 c++ gcc cross-platform stdafx.h visual-studio

我有一个基于Visual Studio C++的程序,它使用预编译的头文件(stdafx.h).现在我们使用gcc 4.x将应用程序移植到Linux.

问题是如何在两种环境中处理预编译的头文件.我用Google搜索但无法得出结论.

显然,我希望stdafx.h在Visual Studio中保留,因为代码库非常大,预编译的头文件可以增加编译时间.

但问题是在Linux中该怎么做.这是我发现的:

  1. 保持stdafx.h原样.gcc比VC++编译代码要快得多(或者只是我的Linux机器更强...... :)),所以我对这个选项很满意.
  2. 这里使用方法- stdafx.h看起来像(USE_PRECOMPILED_HEADER仅为VS 设置):

    #ifdef USE_PRECOMPILED_HEADER
    ... my stuff
    #endif 
    
    Run Code Online (Sandbox Code Playgroud)
  3. 使用此处的方法- 编译VC++ /FI隐式包含stdafx.h在每个cpp文件中.因此,在VS中,您的代码可以轻松切换,无需预编译头文件即可编译,无需更改代码.
    我个人不喜欢依赖,而这个混乱stdafx.h正在推动一个庞大的代码库.因此,该选项对我很有吸引力 - 在你没有的Linux上stdafx.h,同时仍然/FI只能在VS上打开预编译的头文件.

  4. 在Linux上编译stdafx.h只作为预编译头(模仿Visual Studio)

你的意见?还有其他方法可以解决这个问题吗?

Bri*_*ndy 46

您最好还是使用预编译的头文件来进行最快的编译.

您也可以在gcc中使用预编译的头文件. 看到这里.

编译的预编译头将附加一个扩展名.gch而不是.pch.

因此,例如,如果您预编译stdafx.h,您将拥有一个预编译的头文件,当stdafx.h.gch您包含时,将自动搜索该头文件stdafx.h

例:

stdafx.h中:

#include <string>
#include <stdio.h>
Run Code Online (Sandbox Code Playgroud)

a.cpp:

#include "stdafx.h"
int main(int argc, char**argv)
{
  std::string s = "Hi";
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

然后编译为:

> g++ -c stdafx.h -o stdafx.h.gch
> g++ a.cpp
> ./a.out

即使在步骤1之后删除stdafx.h,您的编译也会起作用.

  • 我的意思是,在运行g ++ -c stdafx.h -o stdafx.h.gch之后,你可以删除stdafx.h,你的编译仍然可以工作(g ++ a.cpp).你实际上不会这样做,但我提到它是使用预编译头的证明. (3认同)
  • @idimba:是的,它是选项4,但你在我发布我的答案后三分钟修改了你的问题并添加了#4.无论如何都应该在源代码中包含相应的头文件. (2认同)