简体   繁体   English

在头文件或源文件中包含stdafx.h?

[英]include stdafx.h in header or source file?

I have a header file called stdafx.h and this one is precompiled of course. 我有一个名为stdafx.h的头文件,当然这个是预编译的。 I've read that I should include these files into my .cpp files, but some of these statements are already needed in the header file coming with that. 我已经读过我应该将这些文件包含到我的.cpp文件中,但是随后会出现一些这样的语句。

Should I add the stdafx into my header or into my cpp? 我应该将stdafx添加到我的标题或我的cpp中吗? I thought it was good practise to put it into the header, but I seem to be obliged to put it into the header instead. 我认为将它放入标题是一种好习惯,但我似乎不得不把它放入标题中。

Example: 例:

stdafx contains freeglut. stdafx包含freeglut。
my class header file has an attribute of GLenum. 我的类头文件的属性为GLenum。

Should I include the stdafx into the .h of the class? 我应该将stdafx包含在班级的.h中吗?

stdafx.h should be the first include in EVERY cpp file in your project. stdafx.h应该是项目中每个cpp文件中的第一个包含。


Consider that C++ doesn't compile header files, just Cpp files . 考虑到C ++不编译头文件,只编译Cpp文件

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 . 因此,如果stdafx是cpp文件中的第一个include,那么当它遇到Cpp文件中的头文件时,编译器将拥有头文件所需的所有内容。

eg 例如

You have A.cpp & Ah 你有A.cpp和啊
Ah needs std:string. 啊需要std:string。

you have B.cpp & Bh 你有B.cpp和Bh
Bh needs Ah therefore Bh needs std::string too. Bh需要啊因此Bh也需要std :: string。

Because it's good practice, you put #include <string> in stdafx.h. 因为这是一个很好的做法,所以你将#include <string>放在stdafx.h中。

Your build fails because nothing can see std::string 您的构建失败,因为没有任何东西可以看到std :: string

Now put stafx.h as the first include in A.cpp and B.cpp. 现在将stafx.h作为A.cpp和B.cpp中的第一个包含。
When the compiler hits A.cpp, it picks up the include for <string> , then picks up Ah, and everything is happy because we know what std::string is. 当编译器命中A.cpp时,它会为<string>选择include,然后选择Ah,一切都很开心,因为我们知道std :: string是什么。

The compiler now hits B.cpp, again it includes stdafx first, which brings <string> , then hits Bh, which brings Ah which is again happy because std::string has already been included. 编译器现在命中B.cpp,它再次包含stdafx,它带来<string> ,然后命中Bh,这带来了Ah,因为已经包含了std :: string,所以很高兴。

Hope this helps. 希望这可以帮助。

  • Only include things in your precompiled header which should be there 只包含预编译头中应包含的内容
  • Your precompiled header file must be the first include in every .cpp 您的预编译头文件必须是每个.cpp中的第一个包含文件
  • I would avoid including it in another header in favor of forward declaration 我会避免将它包含在另一个标题中,以支持前向声明

Ask yourself these two questions before including something in stdafx.h 在stdafx.h中包含一些内容之前,先问自己这两个问题

  1. Will this header never be changed by me? 这个标题永远不会被我改变吗?
  2. Do I need this included in every multiple source file? 我是否需要在 每个 多个源文件中包含此内容?

If the answer is "No" to either of those then don't include it. 如果对其中任何一个的回答是“否”,则不包括它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM