25 三 2012
declare and define global variables in header file
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.
#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
2012-03-27 23:50permalink
学习了!
sean
2012-03-30 12:47permalink
靠,这。。。
Bob
2012-04-16 20:39permalink