Should variable definition be in header files?

后端 未结 4 1383
一整个雨季
一整个雨季 2020-12-01 10:30

My very basic knowledge of C and compilation process has gone rusty lately. I was trying to figure out answer to the following question but I could not con

4条回答
  •  旧巷少年郎
    2020-12-01 11:18

    One thing that I've used in the past (when global variables were in vogue):

    var.h file:

    ...
    #ifdef DEFINE_GLOBALS
    #define EXTERN
    #else
    #define EXTERN extern
    #endif
    EXTERN int global1;
    EXTERN int global2;
    ...
    

    Then in one .c file (usually the one containing main()):

    #define DEFINE_GLOBALS
    #include "var.h"
    

    The rest of the source files just include "var.h" normally.

    Notice that DEFINE_GLOBALS is not a header guard, but rather allows declaring/defining the variables depending on whether it is defined. This technique allows one copy of the declarations/definitions.

提交回复
热议问题