Skip to content
Advertisement

How to declare a global variable in an header file and how he need to be in the c file

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:

    /*
     * 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:

 gcc -o g g1.c g2.c

And execution says:

./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
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement