The line #include "test.c"
includes the contents of test.c
in the compilation of main.c
. This causes that compilation to contain the line int globalVariable = 2020;
. This line defines globalVariable
, which causes memory to be reserved for it.
Presumably you compiled both main.c
and test.c
. The compilation of test.c
also contains that line, so it also defines globalVariable
. This is what the linker is complaining about: globalVariable
is defined twice. It is an error to define one thing two times.
Each object should be defined only once. To use it in another file, you just declare it; you do not define it. A declaration that is not a definition gives the compiler information about a thing without asking the compiler to reserve space for it.
To do this, you should remove #include "test.c"
and replace it with the line extern int globalVariable;
.
The usual way this is done is to put that line in a file called test.h
and the put the line #include "test.h"
in both main.c
and test.c
. It is included in main.c
so that the compiler will know about it while compiling main
, which uses globalVariable
. It is included in test.c
as a double-check for correctness: By including test.h
in test.c
, both the declaration in test.h
and the definition in test.c
will be seen by the compiler, and it will check them for consistency. When a declaration just duplicates the information of a definition, the compiler does not complain. When there is a discrepancy, such as different types, it will complain.