C++我是否必须为每个源文件包含标准库?

For*_*vin 7 c++ include standard-library header-files precompiled-headers

我现在有点困惑,因为我计划在我的一个项目中首次包含多个源文件和头文件.
所以我想知道这是否是正确的方法?
我是否必须在每个直接使用它的源文件中包含字符串标头?
那么Visual C++要我包含的"stdafx.hpp"标题呢?

这会是要走的路吗?

main.cpp中

#include "stdafx.hpp"
#include <string> //?
#include <stringLib1.h>
#include <stringLib2.h>
using std::string;

//use a windows.h function here
//use a stringLib1 function here
//use a stringLib2 function here
Run Code Online (Sandbox Code Playgroud)

stringLib1.h

#include "stdafx.hpp"
#include <string>
using std::string;

class uselessClass1
{
public:
    string GetStringBack1(string myString);
};
Run Code Online (Sandbox Code Playgroud)

stringLib1.cpp

#include "stdafx.hpp"

string uselessClass1::GetStringBack1(string myString) {
    return myString;
}
Run Code Online (Sandbox Code Playgroud)

stringLib2.h

#include "stdafx.hpp"
#include <string>
using std::string;

class uselessClass2
{
public:
    string GetStringBack2(string myString);
};
Run Code Online (Sandbox Code Playgroud)

stringLib2.cpp

#include "stdafx.hpp"

string uselessClass2::GetStringBack2(string myString) {
    return myString;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_* A. 6

  1. 好的做法通常是仅在每个文件中包含代码使用的内容。这减少了对其他标头的依赖,并减少了大型项目的编译时间(并且还有助于找出什么取决于什么)

  2. 在头文件中使用包含防护

  3. 不要通过污染全局名称空间来导入所有内容,例如

    using namespace std;
    
    Run Code Online (Sandbox Code Playgroud)

    而是在需要时限定要使用的内容

  4. 除非您使用预编译的标头,否则您不需要stdafx.h在项目中使用。您可以在VS项目属性中控制此行为(C / C ++->预编译头->预编译头


XTF*_*XTF 0

stdafx include 应位于每个 .cpp 文件的顶部,而不应位于 .h 文件中。如果您不想将 #include < string > 放入 stdafx.h 中,则可以将其放入所有其他文件中。