Mr Patience Mr Patience - 1 month ago 21
C++ Question

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.

Answer

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.