Search code examples
cextern

C - usage of extern qualifier


I have following three files. In the header file, I declare a global variable and tried to access it other files using extern. But I got the linker errors.

Header1.h

  #ifndef HEADER1_H
  #define HEADER1_H

  #include<stdio.h>

  int g = 10;
  void test();

  #endif 

test.c

  #include "header1.h"

  extern int g;

  void test()
  {
       printf("from print function g=%d\n", g);
  }

main.c

  #include "header1.h"

  extern int g;

  int main()
  {
     printf("Hello World g=%d\n", g);
     test();
     getchar();
     return 0;
  }

Linker error:

  LNK2005   "int g" (?g@@3HA) already defined in main.obj   
  LNK1169   one or more multiply defined symbols found  

My understanding about extern is that a variable can be defined only once but can be declared multiple times. I think I follow it this way - I defined the global variable g in the header file and tried to access it in the .c files.

Could you please correct my understanding? What actually causes the linker error here? I did not define g multiple times.


Solution

  • You get a multiple definition error because you put the definition in the header file. Because both source files include the header file, that results in g being defined in both places, hence the error.

    You want to put the declaration in the header file and the definition in one source file:

    In header1.h:

    extern int g;
    

    In test.c:

    int g = 10;
    

    And nothing in main.c.