I was having some trouble with "multiple definitions" errors and found this solution that highlights the need to use the extern keyword.
Here is the example used to explain the solution.
FileA.h
#ifndef FILEA_H_
#define FILEA_H_
#include "FileB.h"
void hello();
#endif /* FILEA_H_ */
FileB.cpp
#include "FileB.h"
int wat = 0;
void world()
{
//more code;
}
FileB.h
#ifndef FILEB_H_
#define FILEB_H_
extern int wat; // The solution makes this change with the definition being in FileB.cpp
void world();
#endif /* FILEB_H_ */
Essentially, extern is needed to let the compiler know that wat is defined elsewhere in the code, and to avoid wat being declared multiple times when FileB.h is included multiple times.
MY QUESTION IS, how would wat be declared multiple times without the extern keyword? Specifically, the use of
#ifndef FILEB_H_
#define FILEB_H_
should be enough to avoid multiple definitions, as these header guards would prevent FileB.h from executing more than once. I tried it myself and the extern keyword IS needed to avoid errors. Does it have something to do with the linker? Hopefully this question makes sense.