25 2012

declare and define global variables in header file

Posted by ideal

Generally we declare a global variable in header file (with extern), and define it in .c file. Thus if you need to modify the type of one variable, you need to modify it at both places. In vim’s source code, it uses a good method (actually there are much disscussion about this method on stackoverflow).
In a header file, e.g. globals.h, like this:

#ifndef EXTERN
# define EXTERN extern
# define INIT(x)
#else
# ifndef INIT
#  define INIT(x) x
#  define DO_INIT
# endif
#endif
 
EXTERN    int    rows      INIT(= 25);
EXTERN    int    columns INIT(= 80);

The macro EXTERN can only be defined in one source file, e.g. main.c, like this:

#define EXTERN
#include "globals.h"

In other source files which need to access global variables, just

#include "globals.h"

without define EXTERN. So the global variables are only defined and intialized when compiling main.c.

Tags:

Subscribe to Comments

3 Responses to “declare and define global variables in header file”

  1. #ifdef INIT
    #define INIT_G(x) =x;
    #define EXTERN_G(x) extern x;
    #else
    #ifdef EXTERN
    #define INIT_G(x)
    #define EXTERN_G(x) extern x;

    EXTERN_G(int rows INIT_G(25))
    EXTERN_G(int columns INIT_G(80))

    OceanKing

  2. 学习了!

    sean

  3. 靠,这。。。

    Bob

Leave a Reply

评论: