i have a serious problem to understand how to declare a global variable in an header file and how he need to be in the c file.
In my .h :
extern struct my_global_variable glob;
and on my .c i add to reference it :
struct my_global_variable glob;
Is it like that ?? Thanks you for your answer and have a good day/night depend π
Advertisement
Answer
Declare and define the global variable only in 1 .c
file and use extern
to declare the global variable only in the other .c
files.
Example with 3 source files: g.h
, g1.c
and g2.c
:
JavaScript
βx
/*
* g.h
*/
β
typedef struct my_global_type {
int my_field;
} my_global_type;
β
void g2();
β
/*
* g1.c
*/
β
#include <stdio.h>
β
#include "g.h"
β
my_global_type my_global_variable;
β
int main() {
β
my_global_variable.my_field = 1;
printf("in main: my_global_variable.my_field=%dn", my_global_variable.my_field);
g2();
printf("in main: my_global_variable.my_field=%dn", my_global_variable.my_field);
return 0;
β
}
β
/*
* g2.c
*/
β
β
#include <stdio.h>
β
#include "g.h"
β
extern my_global_type my_global_variable;
β
void g2() {
β
printf("in g2.c: my_global_variable.my_field=%dn", my_global_variable.my_field);
my_global_variable.my_field = 2;
printf("in g2.c: my_global_variable.my_field=%dn", my_global_variable.my_field);
β
}
β
You compile with:
JavaScript
gcc -o g g1.c g2.c
β
And execution says:
JavaScript
./g
in main: my_global_variable.my_field=1
in g2.c: my_global_variable.my_field=1
in g2.c: my_global_variable.my_field=2
in main: my_global_variable.my_field=2
β