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.
int g;(not used here) is a tentative definition. Research tentative definition for details.