Search code examples
cheaderexternglobal

Globals declared in h file and access to them


Just a simple question for understanding:

variable extern int x_glob is declared in header glob.h.

so in every c file that contains functions declared in glob.h using this variable I have to define it agin like this:

extern void func_1( void )
{
  int x_glob;

  glob_x++;
  return();
}

Is that correct?

If I leave off the extern word on the declaration of x_glob in glob.h, I don't need the definition.

Why not leaving away the extern word in the header file?

Maybe this question sounds stupid - my goal is to get a better structure into my programming as the projects grow.


Solution

  • No, this is wrong. With int x_glob inside a function you declare a local, automatic variable. This overrides any global variable.

    But in precisely one .c file you must declare the global variable:

    // main.c
    
    int x_glob;
    

    This creates one variable that can now be used by all modules. The extern version of the variable only tells the compiler when compiling the other modules that somewhere there exists this variable and it will be found upon linking the modules into the excutable.

    Personally I prefer the following set-up:

    // glob.h
    #ifndef EXTERN
    #define EXTERN extern
    #endif
    EXTERN int x_glob;
    
    // module.c
    #include "glob.h"
    
    // main.c
    #define EXTERN
    #include "glob.h"
    

    In all modules x_glob will be known as extern and in main it will not be extern and so will declare the storage for the global variable.