gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:29:25 25 4
gpt4 key购买 nike

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

那是要走的路吗?

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

stringLib1.h

#include "stdafx.hpp"
#include <string>
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 <string>
using std::string;

class uselessClass2
{
public:
string GetStringBack2(string myString);
};

stringLib2.cpp

#include "stdafx.hpp"

string uselessClass2::GetStringBack2(string myString) {
return myString;
}

最佳答案

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

  2. 使用 include guards在你的头文件中

  3. 不要通过 polluting 导入所有内容全局命名空间,例如

    using namespace std;

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

  4. 您的项目中不需要stdafx.h unless you're using precompiled headers .您可以在 VS 项目属性(C/C++ -> 预编译 header -> 预编译 header )中控制此行为

关于C++ 我必须为每个源文件包含标准库吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25870961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com