How can I use variables in multiple files?

后端 未结 3 1994
旧时难觅i
旧时难觅i 2021-01-16 04:51

I want do define a variable in the header and be able to use it in multiple files. e.g. have variable a defined somewhere and be able to use/change it in both

3条回答
  •  深忆病人
    2021-01-16 05:51

    In the header file, write this:

    extern int a;
    extern float b;
    

    This will declare the variables.

    In one of the CPP files, write this:

    int a = 1;
    float b = 2.2;
    

    This will define the variables. It does not matter in which CPP file you put the definitions, as long as the variables are defined exactly once.

提交回复
热议问题