How can I use variables in multiple files?

后端 未结 3 1973
旧时难觅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:48

    First off, don't do this. Global mutable state is usually a bad thing.

    The problem is that once the linker finishes combining the files in your include statments, it has seen this twice, once in main.cpp and once in vars_main.cpp:

    int a = 1;
    float b = 2.2;
    

    If you only put this in the header file, it shows up in multiple translation units, once for each cpp file that includes your header. It's impossible for the compiler to know which a and b you're talking about.

    The way to fix this is to declare them extern in the header:

    extern int a;
    extern float b;
    

    This tells the compiler that a and b are defined somewhere, not necessarily in this part of the code.

    Then, in one of your cpp files you would define them:

    int a = 1;
    float b = 2.2;
    

    That way, there's one well-defined place for the storage for a and b to live, and the compiler can connect the dots properly.

提交回复
热议问题