Handling stdafx.h in cross-platform code

2019-01-29 22:48发布

I have a Visual Studio C++ based program that uses pre-compiled headers (stdafx.h). Now we are porting the application to Linux using gcc 4.x.

The question is how to handle pre-compiled header in both environments. I've googled but can not come to a conclusion.

Obviously I want leave stdafx.h in Visual Studio since the code base is pretty big and pre-compiled headers boost compilation time.

But the question is what to do in Linux. This is what I found:

  1. Leave the stdafx.h as is. gcc compiles code considerable faster than VC++ (or it is just my Linux machine is stronger ... :) ), so I maybe happy with this option.
  2. Use approach from here - make stdafx.h look like (set USE_PRECOMPILED_HEADER for VS only):

    #ifdef USE_PRECOMPILED_HEADER
    ... my stuff
    #endif 
    
  3. Use the approach from here - compile VC++ with /FI to implicitly include stdafx.h in each cpp file. Therefore in VS your code can be switched easily to be compiled without pre-compiled headers and no code will have to be changed.
    I personally dislike dependencies and the mess stdafx.h is pushing a big code base towards. Therefore the option is appealing to me - on Linux you don't have stdafx.h, while still being able to turn on pre-compiled headers on VS by /FI only.

  4. On Linux compile stdafx.h only as a precompiled header (mimic Visual Studio)

Your opinion? Are there other approaches to treat the issue?

10条回答
你好瞎i
2楼-- · 2019-01-29 23:45

I used option 3 last time I needed to do this same thing. My project was pretty small but this worked wonderfully.

查看更多
欢心
3楼-- · 2019-01-29 23:45

I'd either go for option 4 or option 2. I've experimented with precompiled headers on both various VS versions and GCC on Linux (blog posts about this here and here). In my experience, VS is a lot more sensitive to the length of the include paths, number of directories in the include path and the number of include files than G++ is. When I measured build times properly arranged precompiled headers would make a massive difference to the compile time under VS whereas G++ was pretty much unimpressed by this.

Actually, based on the above what I did the last time I worked on a project where this was necessary to rein in the compile time was to precompile the equivalent of stdafx.h under Windows where it made sense and simply used it as a regular file under Linux.

查看更多
唯我独甜
4楼-- · 2019-01-29 23:49

Very simple solution. Add a dummy file entry for "stdafx.h" in Linux environment.

查看更多
冷血范
5楼-- · 2019-01-29 23:52

Since stdafx.h is by default all the Windows-specific stuff, I've put an empty stdafx.h on my other platform. That way your source code stays identical, while effectively disabling stdafx on Linux without having to remove all the #include "stdafx.h" lines from your code.

查看更多
登录 后发表回答