简体   繁体   English

在C ++中包含标头

[英]Include headers in c++

I have something like this: 我有这样的事情:

//main.cpp
#include <add.h>

cin >> a;
cin >> b;
cout << add(a,b);


//add.h
#ifndef add_h
#define add_h

int add(int a, int b);

#endif 


//add.cpp
int add(int a, int b){
    return a+b;
}

Should I include add.h in add.cpp too or I can include it only in main.cpp? 我也应该在add.cpp中包含add.h还是只能在main.cpp中包含它?
I'm asking because I saw that somewhere and I'm curious which way is better. 我问是因为我在某个地方看到了那个,我很好奇哪种方法更好。

You may include it but it is not obligatory here. 您可以包括它,但在这里不是必须的。

Usually it is good practice to have all declarations included in object defining it (it gives you possibility to define functions in any order). 通常,将所有声明包含在定义它的对象中是一种很好的做法(它使您可以按任何顺序定义函数)。

Here is an example: if you have add and combined_add (function calling add() in the middle) you are forced to define add before combined_add. 这是一个示例:如果您具有add和Combined_add(中间调用add()的函数),则必须在Combined_add之前定义add。 when you have include header at the top of your file you can define combined_add before add without compiler's error. 当文件顶部包含头文件时,可以在添加之前定义Combined_add,而不会出现编译器错误。

Should I include add.h in add.cpp too or I can include it only in main.cpp? 我也应该在add.cpp中包含add.h还是只能在main.cpp中包含它?

In this case you don't have to no. 在这种情况下,您不必没有。

int add(int a, int b);

The moment a definition of this declaration of add becomes important is at the linking stage. add声明的定义很重要的时刻是在链接阶段。 The linker checks all generated object files (intermediate compiled source files ( main.o and add.o in this case ) and if one of these object files contains a definition (and thus an implementation) for add then the linker is satisfied and that definition is used. The cpp file doesn't have to know anything about the declaration in the header file since a definition by itself is already a declaration. 链接器检查所有生成的目标文件(中间编译的源文件(在这种情况下为main.o和add.o),并且如果这些目标文件之一包含要add的定义(因此是实现),则链接器满足且该定义使用cpp文件不必知道头文件中的声明,因为定义本身已经是一个声明。

To make it more clear, as long as you have a declaration and you know your linker will find the definition of that declaration you don't even need a header file : 更明确地说,只要您有一个声明,并且知道链接器会找到该声明的定义,您甚至都不需要头文件:

Main.cpp : Main.cpp

extern int add(int a, int b);

cin >> a;
cin >> b;
cout << add(a,b);

Add.cpp : Add.cpp

int add(int a, int b){
    return a+b;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM