How to declare a global variable that could be used in the entire program

后端 未结 9 1045
别那么骄傲
别那么骄傲 2020-12-13 14:52

I have a variable that I would like to use in all my classes without needing to pass it to the class constructor every time I would like to use it. How would I accomplish th

9条回答
  •  佛祖请我去吃肉
    2020-12-13 15:28

    global.h
    extern int myVar;
    
    global.cpp
    #include "global.h"
    int myVar = 0;  // initialize
    
    class1.cpp
    #include "global.h"
    ...
    
    class2.cpp
    #include "global.h"
    ...
    
    class3.cpp
    #include "global.h"
    ...
    

    MyVar will be known and usable in every module as a global variable. You do not have to have global.cpp. You could initialize myVar in any of the class .cpp's but I think this is cleaner for larger programs.

提交回复
热议问题