I already know of include guards, but here are some issues i’d like to figure out:
Example 1
Foo.h
int SumOfNums(int i, int j);
Foo.cpp
#include "Foo.h"
int SumOfNums(int i, int j){
return i+j;
}
main.cpp
#include "Foo.h"
#include "Foo.h"
int main(){
SumOfNumbs(5,10);
}
This will compile and run ok.
Example 2
Foo.h
int SumOfNums(int i, int j);
int i;
Foo.cpp
#include "Foo.h"
int SumOfNums(int i, int j){
return i+j;
}
main.cpp
#include "Foo.h"
int main(){
SumOfNumbs(5,10);
}
Redefinition of ‘i’ according to compier.
Example 3
Foo.h
int SumOfNums(int i, int j);
enum FooBar{FOO, BAR};
Foo.cpp
#include "Foo.h"
int SumOfNums(int i, int j){
return i+j;
}
main.cpp
#include "Foo.h"
int main(){
SumOfNumbs(5,10);
}
This will compile and run ok.
Example 4
Foo.h
int SumOfNums(int i, int j);
enum FooBar{FOO, BAR};
Foo.cpp
#include "Foo.h"
int SumOfNums(int i, int j){
return i+j;
}
main.cpp
#include "Foo.h"
#include "Foo.h"
int main(){
SumOfNumbs(5,10);
}
Redefinition of FooBar according to compiler.
To sum it up:
Example 1 – Why can Foo.h be included twice in main.cpp, when there’s no include guards?
Example 2 – How does the int variable differ from the function header?
Example 3 – Why doesn’t the linker complain when there’s one definition of FooBar in Foo.cpp and one in main.cpp?
Example 4 – What’s the difference between this and Example 1?
Because in that case, it only declares a function. You can have as many declarations as you want.
That’s also a definition and thus breaks the one definition rule.
Defining types across translation units is fine.
You’re defining the same type twice in the same translation unit – not permitted.