简体   繁体   中英

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?
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. when you have include header at the top of your file you can define combined_add before add without compiler's error.

Should I include add.h in add.cpp too or I can include it only in 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. 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.

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 :

extern int add(int a, int b);

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

Add.cpp :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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