include stdafx.h in header or source file?

后端 未结 2 1550
梦谈多话
梦谈多话 2020-12-10 12:46

I have a header file called stdafx.h and this one is precompiled of course. I\'ve read that I should include these files into my .cpp files, but some of these statements are

2条回答
  •  悲哀的现实
    2020-12-10 13:12

    stdafx.h should be the first include in EVERY cpp file in your project.


    Consider that C++ doesn't compile header files, just Cpp files.

    Therefore if the stdafx is the first include in the cpp file, then the compiler will have everything the header file needs, when it hits the header-file in the Cpp file.

    e.g.

    You have A.cpp & A.h.
    A.h needs std:string.

    you have B.cpp & B.h
    B.h needs A.h therefore B.h needs std::string too.

    Because it's good practice, you put #include in stdafx.h.

    Your build fails because nothing can see std::string

    Now put stafx.h as the first include in A.cpp and B.cpp.
    When the compiler hits A.cpp, it picks up the include for , then picks up A.h, and everything is happy because we know what std::string is.

    The compiler now hits B.cpp, again it includes stdafx first, which brings , then hits B.h, which brings A.h which is again happy because std::string has already been included.

    Hope this helps.

提交回复
热议问题