源函数的头文件和include 我是C++的新手,来自一种解释性语言。我很难理解头文件与库和依赖关系的关系。
例如,假设我拥有项目的主体:源函数的头文件和include 我是C++的新手,来自一种解释性语言。我很难理解头文件与库和依赖关系的关系。,c++,include,header-files,C++,Include,Header Files,例如,假设我拥有项目的主体: #include <vector> //----------------------------define some auxiliary function which deals with vectors void A(std::vector<int> &vect) { vect.clear(); } //----------------------------main body int main() { st
#include <vector>
//----------------------------define some auxiliary function which deals with vectors
void A(std::vector<int> &vect)
{
vect.clear();
}
//----------------------------main body
int main()
{
std::vector<int> vect = {1,2,3}
A(vect);
return 0 ;
}
现在假设我想在一个单独的.cpp文件中定义辅助函数A,并且仍然能够从主.cpp文件调用它。我的问题是-对于这个项目,我是否必须包含在所有使用该库中的内容的.cpp文件中?如果是,我还需要在我的主文件中包括吗
我想我了解头文件是如何工作的,但是如果我有几个文件使用同一个库中的元素,那么会发生什么情况仍然不清楚。只有使用向量组件的文件需要包含它。在包含其他文件时,也可以包含零部件 例如: 例h Example.cp @Vivick的评论
您通常也会在main中包含,以避免需要查找包含哪个库的头文件。您不必在所有.cpp文件中都包含。如果在Example.h或Example.cpp中包含它们,并且只在主文件中包含其中一个,如include Example.h或Example.cpp,那么也可以在主文件中使用向量。假设您创建了a.h和a.cpp a、 h a、 cpp 任何包含a.h的人都会附带包含但不包括每个模块。h仍然需要包含其自身的所有依赖项,即如果您在某个地方需要std::vector,则必须包含它,否则如果在其他上下文中使用,您的代码可能无法再编译。包含是可传递的。include foo.h只是将foo.h的内容替换为include指令 这是正确的,但不好:
// foo.h
#include <vector>
std::vector<int> v;
// bar.h
#include "foo.h"
// main.cpp
#include "bar.h"
std::vector<int> x;
int main() {}
有些人建议最后包含标准库标题。以这种方式,如果例如foo.h忘记包含,您将得到一个错误。有时头不需要类型的完整定义,而只需要一个声明。在这种情况下,可以使用前向声明来减少编译时间。然后,仅通过包含标头在源中提供定义。例如:
// foo.h
struct bar; // forward declaration
struct foo {
bar* p; // pointer, need only declaration, no definition!
void do_something();
}
// foo.cpp
#include "bar.h"
void foo::do_something() {
bar b; // create instance, needs definition
// ...
}
PS:您不必担心太频繁地包含标题。标头通过所谓的包含防护装置针对多个包含进行防护:
// moo.h
#ifndef MOO_HEADER_INCLUDE_GUARD
#define MOO_HEADER_INCLUDE_GUARD
// the actual contents
#endif
如果在一个翻译单元中,同一标题包含两次,预处理器将处理包含,预处理器将看到符号MOO_header_INCLUDE_GUARD已定义,并跳过标题的内容。仅使用向量的文件需要包含它。@MathewHD yes,但是,所有使用它的文件都必须单独包含它吗?尽管在main中也包含vector是一种很好的做法,以避免查找哪个头包含在示例main中使用的向量,但不包含头。如果我将第一行保留在main中,但将Example.h替换为其他内容,那么main将被破坏。你应该包括你所使用的,而不是依赖其他人的包括includes@Vivick并不是说OP做不到。我只是想说明,您不必在每个脚本中都包含,而是可以在头文件中使用一个include。你至少应该提到,它已经被添加为一条评论,如果需要的话,我可以在答案中加入评论。
#include "a.h" // include your own declarations
void A(std::vector<int> &vect)
{
...
}
// foo.h
#include <vector>
std::vector<int> v;
// bar.h
#include "foo.h"
// main.cpp
#include "bar.h"
std::vector<int> x;
int main() {}
// foo.h
#include <vector>
std::vector<int> v;
// bar.h
#include "foo.h"
// main.cpp
#include "bar.h"
#include <vector>
std::vector<int> x;
int main() {}
// foo.h
struct bar; // forward declaration
struct foo {
bar* p; // pointer, need only declaration, no definition!
void do_something();
}
// foo.cpp
#include "bar.h"
void foo::do_something() {
bar b; // create instance, needs definition
// ...
}
// moo.h
#ifndef MOO_HEADER_INCLUDE_GUARD
#define MOO_HEADER_INCLUDE_GUARD
// the actual contents
#endif