On this page
include defines
#include
like python or Java import
#include
works as a literal copy and paste
Ilk.h:
class Milk{
...
}
main.cpp
#include "Milk.h" // like Ctrl+C and Ctrl+V
int main(){
}
Result:
class Milk{
...
}
int main(){
}
including headers from other directories
#include "headers/myHeader.h"
#include "../moreHeaders/myOtherHeader.h"
ok but what about this
A.h
B.h
class A{
...
}
#include A.h
class B{
...
}
main.cpp
#include A.h
#include B.h
int main(){
...
}
You get this error: redefinition of ‘class A’
Result:
// from the #include A.h
class A{
...
}
// from the #include B.h
class A{
...
}
class B{
...
}
int main(){
...
}
Why are there two A classes??
In main.cpp we also have a `#include A.h` so we copy A.h into main.cppHow do we get around this problem?
Header guards
for now, don’t worry so much about what the code means. Just know wrapping our classes fixes the problem
#ifndef FILENAME_
#define FILENAME_
...
// your code in here
...
#endif // FILENAME_H_
If we wrap A.cpp and B.cpp with this it will first check if a file has already been included before
A.h
B.h
#ifndef A_H_
#define A_H_
class A{
...
}
...
#endif // A_H_
#ifndef B_H_
#define B_H_
#include A.h
class B{
...
}
#endif // B_H_
main.cpp
#include A.h
#include B.h
int main(){
A a_obj;
B b_obj;
}
Step-by-step breakdown
the first line in main.cpp is `#include A.h` so we copy class A into main.cpp like before.Result:
// from the #include A.h
class A{
...
}
// from the #include B.h
// NOTE: there is no class A because of the header guard
class B{
...
}
int main(){
...
}
NOTE: Header guards must ALWAYS be the first and last thing in every
.h
file.
#define
Literal find + replace
#define PIN_NUM 10 // like find and replace
int main(){
int newPinNum = PIN_NUM+2;
}
Result:
int main(){
int newPinNum = 10+2;
}
Can wrap functions
#define READ(data) read(port, data, 2) // has pre filled arguments
int main(){
READ(stuff);
}
Result:
int main(){
read(port, stuff, 2);
}