0

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.

1
  • "a variable can be defined only once" is true, yet as a global int g; (not used here) is a tentative definition. Research tentative definition for details. Commented Apr 19, 2018 at 22:01

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It is worth reminding that a #include statement, for most intents and purposes, is identically equivalent to copy/pasting that file's content into the file doing the including.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.