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

后端 未结 7 1455
情话喂你
情话喂你 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 10:11

    What is happening is that each of the variables from Variables.h are given global scope for each of the individual c files. When the linker compiles all the c files, it sees multiple variables with the same name.

    If you are wanting to use variables from the header file as global variables, then you will have to use the keyword "extern" in front of all of them, and in the main file don't use the keyword extern.

    main c:

    int n_MyVar;
    

    other files:

    extern int n_MyVar;
    

    You can create two files Variables.h and EVariables.h, or just declare the variables in the main.cpp file.

    A much better way to do this is to create a class of Variables and pass a reference to the class.

提交回复
热议问题