C ++每个源文件都必须包含标准库吗?
C ++每个源文件都必须包含标准库吗?
我目前有点困惑,因为我计划在我的一个项目中首次包含多个源文件和头文件。
所以我想知道这是否是正确的方法?
我是否必须在每个直接使用它的源文件中包含string头文件?
那么Visual C ++想让我包含的\"stdafx.hpp\"头文件该怎么办?
这是正确的方法吗?
main.cpp
#include "stdafx.hpp" #include //? #include #include using std::string; //use a windows.h function here //use a stringLib1 function here //use a stringLib2 function here
stringLib1.h
#include "stdafx.hpp" #include using std::string; class uselessClass1 { public: string GetStringBack1(string myString); };
stringLib1.cpp
#include "stdafx.hpp" string uselessClass1::GetStringBack1(string myString) { return myString; }
stringLib2.h
#include "stdafx.hpp" #include using std::string; class uselessClass2 { public: string GetStringBack2(string myString); };
stringLib2.cpp
#include "stdafx.hpp" string uselessClass2::GetStringBack2(string myString) { return myString; }
admin 更改状态以发布 2023年5月21日
stdafx.h
头文件在VS中启用预编译头文件时需要。(阅读这篇文章)
你只需要在你的.cpp
文件中作为第一个 include 引入stdafx.h
。
关于头文件和cpp文件(成对出现),在头文件中包括声明所必需的内容,并在cpp文件中包括所有其他内容(对定义必要的)。还要在其cpp对中包括相应的头文件。并使用include guards。
myclass.h
#ifndef MYCLASS_H // This is the include guard macro #define MYCLASS_H #includeusing namespace std; class MyClass { private: string myString; public: MyClass(string s) {myString = s;} string getString(void) {return myString;} void generate(); }
myclass.cpp
#include// VS: Precompiled Header // Include the header pair #include "myclass.h" // With this one gets included too // Other stuff used internally #include #include void MyClass::generate() { vector myRandomStrings; ... cout << "Done\n"; } #endif
然后在main(...)
中,您只需要括引myclass.h
并调用generate()
函数即可。
-
通常最好的做法是在每个文件中只包含您的代码需要的内容。这减少了对其他标头的依赖,并且在大型项目中减少了编译时间(也有助于找出谁依赖于谁)
-
在您的标头文件中使用包含保护(include guards)
-
不要通过污染全局命名空间来导入所有内容,例如:
using namespace std;
而是在需要时限定您要使用的内容
-
除非您使用预编译头文件,否则在您的项目中不需要
stdafx.h
。您可以在VS项目属性(C/C++ -> 预编译头文件 -> 预编译头)中控制此行为