C ++是否必须为每个源文件包括标准库? [英] C++ Do I have to include standard libraries for every source file?

查看:104
本文介绍了C ++是否必须为每个源文件包括标准库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm a bit confused at the moment because I'm planning to include multiple source and header files for the first time in one of my projects.
So I'm wondering if this would be the right approach?
Do I have to include the string header in every source file that uses it directly?
And what about the "stdafx.hpp" header that Visual C++ wants me to include?

那是走的路吗?

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. 一个好的实践通常是只包含每个文件中代码所使用的内容.这样可以减少对其他标头的依赖,并减少大型项目的编译时间(并且还有助于找出什么取决于什么)

  1. A good practice is usually to include only what your code uses in every file. That reduces dependencies on other headers and, on large projects, reduce compilation times (and also helps finding out what depends on what)

在头文件中使用包括警卫

不要通过污染<全局名称空间,例如

Don't import everything by polluting the global namespace, e.g.

using namespace std;

而是在需要时限定您打算使用的东西

but rather qualify what you intend to use when you need it

您的项目除非您不需要stdafx.h重新使用预编译的标头.您可以在VS项目属性( C/C ++->预编译头文件->预编译头文件)

You don't need stdafx.h in your project unless you're using precompiled headers. You can control this behavior in the VS project properties (C/C++ -> Precompiled Headers -> Precompiled Header)

这篇关于C ++是否必须为每个源文件包括标准库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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