You should use 'extern
' while declaring a global variable in header file.
Define it in any one of *.c
file.
This should fix the issue.
For more on header files, read How do I use extern to share variables between source files?
Frage
I have 3 *.c
files (file1.c
, file2.c
and file3.c
) and 1 *.h
file (file3.h
) in a project (Visual Studio).
/*******************************
file3.h
********************************/
#ifndef FILE3_H
#define FILE3_H
int gintVariable = 400;
#endif
/*******************************
file1.c
********************************/
#include "file3.h"
#include <stdio.h>
#include <conio.h>
int modifyGlobalVariable(void);
void printGlobalVariable(void);
int main(void)
{
modifyGlobalVariable();
printGlobalVariable();
printf("Global variable: %d\n", gintVariable++);
getch();
return 0;
}
/*******************************
file2.c
********************************/
#include "file3.h"
int modifyGlobalVariable(void)
{
return gintVariable++;
}
/*******************************
file3.c
********************************/
#include "file3.h"
#include <stdio.h>
void printGlobalVariable(void)
{
printf("Global: %d\n", gintVariable++);
}
When I build the solution in VS, it is giving error as "_gintVariable already defined in file1.obj"
.
I did check in the pre-processor output, the gintVariable is included in all the *.c files even though I have included include guards.
What mistake I am doing?
Lösung
You should use 'extern
' while declaring a global variable in header file.
Define it in any one of *.c
file.
This should fix the issue.
For more on header files, read How do I use extern to share variables between source files?
Andere Tipps
Including guards prevents multiple inclusion (or, more precisely, multiple compilation of the .h file content) in a single translation unit.
It is useful against this problem:
/* glob.h */
#ifndef H_GLOB
#define H_GLOB
struct s { int i; };
#endif
/* f.h */
#ifndef H_F
#define H_F
#include "glob.h"
struct s f(void);
#endif
/* g.h */
#ifndef H_G
#define H_G
#include "glob.h"
struct s g(void);
#endif
/* c.c */
#include "f.h" /* includes "glob.h" */
#include "g.h" /* includes "glob.h" */
void c(void) {
struct s s1 = f();
struct s s2 = g();
}
The inclusions is like a diamond:
glob.h / \ f.h g.h \ / c.c