Is there a way to use pre-compiled headers in VC++

2019-01-14 08:46发布

I've got a bunch of legacy code that I need to write unit tests for. It uses pre-compiled headers everywhere so almost all .cpp files have a dependecy on stdafx.h which is making it difficult to break dependencies in order to write tests.

My first instinct is to remove all these stdafx.h files which, for the most part, contain #include directives and place those #includes directly in the source files as needed.

This would make it necessary to turn off pre-compiled headers since they are dependent on having a file like stdafx.h to determine where the pre-compiled headers stop.

Is there a way to keep pre-compiled headers without the stdafx.h dependencies? Is there a better way to approach this problem?

9条回答
Melony?
2楼-- · 2019-01-14 09:23

When you normally use precompiled headers, "stdafx.h" serves 2 purposes. It defines a set of stable, common include files. Also in each .cpp file, it serves as a marker as where the precompiled headers end.

Sounds like what you want to do is:

  • Leave precompiled header turned on.
  • Leave the "stdafx.h" include in each .cpp file.
  • Empty out the includes from "stdafx.h".
  • For each .cpp file, figure out which includes were needed from the old "stdafx.h". Add these before the #include "stdafx.h" in each .cpp file.

So now you have the minimal set of dependancies, and you still are using precompiled headers. The loss is that you are not precompiling your common set of headers only once. This would be a big hit for a full rebuild. For development mode, where you are only recompiling a few files at a time, it would be less of a hit.

查看更多
爷、活的狠高调
3楼-- · 2019-01-14 09:24

Pre-compiled headers are predicated on the idea that everything will include the same set of stuff. If you want to make use of pre-compiled headers then you have to live with the dependencies that this implies. It comes down to a trade-off of the dependencies vs the build speed. If you can build in a reasonable time with the pre-compiled headers turned off then by all means do it.

Another thing to consider is that you can have one pch per library. So you may be able to split up your code into smaller libraries and have each of them have a tighter set of dependencies.

查看更多
仙女界的扛把子
4楼-- · 2019-01-14 09:32

No, there is probably NOT a better way.

However, for a given individual .cpp file, you might decide that you don't need the precompiled header. You could modify the settings for that one .cpp file and remove the stdafx.h line.

(Actually, though, I don't how the pre-compiled header scheme is interferring with the writing of your unit tests).

查看更多
登录 后发表回答