Splitting Files

Header Files vs C++ Files

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){
...
}

Multiple Header Files

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

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

Takeaways

  1. Multiple function implementation: linking fails
  2. Multiple function prototypes/header files: compilation fails
    1. Can use header guards to prevent this
      1. function implementation goes to .cpp
      2. protypes and data structs go to .h
      3. main contains source code

Classes and Objects (OOP)

Data Structures