A global variable must exist somewhere, and only in one place. That means it needs to be declared in one place only.
Remember: H files just tell the compiler that things exist somewhere. C files provide the actual definition of those things.
Let's say your global belongs nowhere else, we'll add a globals.c
:
#include "globals.h"
int g_myGlobal;
There should be a corresponding globals.h
:
#ifndef _GLOBALS_H
#define _GLOBALS_H
extern int g_myGlobal;
#endif // _GLOBALS_H
It is almost certainly an error to have a global variable declared in a .h
file without extern
. If you do such a thing, the compiler will try to declare that variable in every C file that includes that header, which will lead to "multiple definition" errors at link-time. (I'm assuming this is why you were asking "foo.c always include bar123.h?", and explains why it should not matter.)
main.h
:
#include "globals.h"
int main() {
g_myGlobal = 42;
}