在头文件或源文件中包括stdafx.h? [英] include stdafx.h in header or source file?

查看:327
本文介绍了在头文件或源文件中包括stdafx.h?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为stdafx.h的头文件,这个是预编译的。
我读过,我应该将这些文件包含在我的.cpp文件中,但是在头文件中已经包含了这些语句。



我应该添加stdafx到我的标题或我的cpp?



例如:



stdafx包含freeglut。

我的类头文件具有GLenum的属性。



我应该包括stdafx stdafx.h 。 应该是您项目中每个cpp文件中的第一个include。




考虑 C ++ doesn



因此,如果stdafx是cpp文件中的第一个include,那么编译器将拥有所有的头文件



例如



>你有A.cpp& A.h.

A.h需要std:string。



您有B.cpp& Bh

Bh需要啊因此Bh也需要std :: string。



因为这是一个很好的做法,你把 #include < string>



您的构建失败,因为没有可以看到std :: string



现在将stafx.h作为A.cpp和B.cpp中的第一个include。

当编译器命中A.cpp时,它会选择< string> ,然后选择Ah,一切都很高兴,因为我们知道std :: string是什么。



现在点击B.cpp,它再次包括stdafx第一,它带来< string> ,然后命中Bh,这带来了Ah再次很高兴,因为std :: string已经



希望这有帮助。


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 already needed in the header file coming with that.

Should I add the stdafx into my header or into my 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.
my class header file has an attribute of GLenum.

Should I include the stdafx into the .h of the class?

解决方案

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 headerfile 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 practise, you put #include <string> 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 incldue for <string>, 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 <string>, then hits B.h, which brings A.h which is again happy because std::string has already been included.

Hope this helps.

这篇关于在头文件或源文件中包括stdafx.h?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆