C language of global variables defined in the header file

  Under normal circumstances, are defined in the C file global variables declared in the header file, however, if the global variables we define to be using a lot of C files, then the global variables defined in the header file which will be a lot easier, that in the end is how to achieve?

os_var.c file contents

1  #define OS_GLOBALS
 2 #include "os.h"

os.h file contents

1 #ifdef OS_GLOBALS
2 #define OS_EXT
3 #else
4 #define OS_EXT extern
5 #endif

  os.h defined in many global variables, but os.h they need to be called a lot of c file, if not special treatment, then repeated the error global variable definition will appear in order to define global variables in os.h, os.h macro definition at the beginning of the file content above os.h added, and the global variable before the words "OS_EXT", and then define a os_var.c single file, comprising os.h then, and only in this document which define the macro "OS_GLOBALS", in other documents contained in os.h, do not define the macro "OS_GLOBALS", then at compile time, only the front OS_EXT global variable os_var.c inside os.h inside it expands empty, in front of a global variable os.h other documents contained in OS_EXT will be expanded as extern, that is a statement, rather than the definition, thus achieving a global variable defined in os.h in.

  os.h is uC / OS-III of general file header, which defines a number of global variables, and this header will be called a lot of document C, in order to prevent duplicate definition of a global variable, it has taken the above method , i.e., a new single file C os_var.c, and C in this document which defines OS_GLOBALS macro, then the header containing os.h. Os_var.c then only at compile time, os.h inside the global variable is defined, os.h other variables are declared inside the c file, because the other C file we will not define this macro OS_GLOBALS.

Guess you like

Origin www.cnblogs.com/SGY1593279715/p/10939367.html