On splitting code between files, why do we need .h files and .cpp files? Why can’t we just have a print.cpp file that we add to main.cpp?
#include "print.cpp"
int main(){
...
}
#include <iostream>
void printNum(int){
...
}
print.cpp is pasted into main.cpp. Therefore, the function exists in both files. When you compile the two files, the output object files both have the function definition in them.What happens if we include header files more than once? Below we have a header file a.h where a struct is defined. In a separate file, I want to print a coordinate.
struct coordinate{
int x, y;
}
#include "a.h" // so the function knows what a coordinate is
void print(coordinate c)
#include <iostream>
#include "b.h"
void print(coordinate c){
cout << "x = " << c.x << " y = " << c.y << endl;
}
#include "a.h"
#include "b.h"
int main(){
coordinate c1;
c1.x = 100;
c1.y = 200;
print(c1);
}
In this case, we have the coordinate structure pasted twice into main: one comes from the a.h file and the second comes from the b.h file. Unlike the previous section example, which caused a linking error, this time we get a compilation error.
Header guards help to guard your compiler from defining the same thing more than once. Below, the example header guard is called A_H ← it’s its name
#ifndef A_H
#define A_H
struct coordinate{
int x, y;
}
#endif
.cpp.h