How can I avoid the LNK2005 linker error for variables defined in a header file?

后端 未结 7 1394
情话喂你
情话喂你 2020-12-19 09:28

I have 3 cpp files that look like this

#include \"Variables.h\"
void AppMain() {
    //Stuff...
}

They all use the same variables inside th

7条回答
  •  囚心锁ツ
    2020-12-19 09:56

    This is because the compiler compiles each .cpp file separately, creating a .obj file for each one. Your header appears to have something like:

    int slider;
    

    When this is included into each of your three .cpp file, you get three copies of the int slider variable, just as if you had declared it in each .cpp file. The linker complains about this because you haven't have three different things with the same name.

    What you probably want to do is change your header file to read:

    extern int slider;
    

    This tells the compiler that there is a slider variable somewhere, but possibly not here, and lets the linker figure it out. Then, in one .cpp file:

    int slider;
    

    gives the linker one actual variable to link.

提交回复
热议问题