1

I'm new to C, still struggling in understanding global variable,below is my code:

//test.c

int globalVariable = 2020;
//main.c

#include <stdio.h>
#include "test.c" // I just include c file for demo purpose

int main()
{
   printf("Value is %d", globalVariable);
}

and there is comile error which says globalVariable already defined in Main.obj

but we know that any global variable or function declared without the static attribute is public and can be accessed by any other module, I didn't define globalVariable in main.c, where did I go wrong?

2 Answers2

1

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.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • btw, you mean I should put `int globalVariable;` in `test.h`, and no need to use extern? –  Aug 24 '20 at 15:44
0

first if you define a global variable and include it inside main.c. once you compile main.c, then compiler would transfer main.c into a main.obj as well as the included source file test.c into another obj file test.obj simultaneously. then linker want to put test.obj and main.obj into one and find globalVariable was define twice. so if you want to avoid this error, just use extern int globalVariable in main.c, then linker will know it is declaration rather than definition and won't allocate memory space for globalVariable in main.c.

brushmonk
  • 109
  • 7