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

I have 3 cpp files that look like

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

They all use the same variables inside them, so they have the same headers, but I get things like this.

1>OnTimer.obj : error LNK2005: "int slider" (?slider@@3HA) already defined in AppMain.obj

Why is this?

+5
source share
6 answers

Keep in mind that #include roughly corresponds to cutting and pasting the included file into the source file that includes it (this is a crude analogy, but you get the point). This means that if you have:

int x;  // or "slider" or whatever vars are conflicting

, , x, .

, , extern, .cpp , .cpp .

Variables.h:

extern int x;

SomeSourceFile.cpp

int x;

, globals, , .

+16

"int slider" ? , ...

#ifndef _VARIABLES_H_
#define _VARIABLES_H_

int slider;

#endif

, , ( ), , :

namespace {
    int slider;
}

, , .

+3

, .cpp , .obj . - :

int slider;

.cpp, int slider, .cpp. , .

, , , :

extern int slider;

, slider -, , , , . .cpp:

int slider;

.

+3

, , Variables.h c. c, .

, "extern" , extern.

main c:

int n_MyVar;

:

extern int n_MyVar;

Variables.h EVariables.h main.cpp.

- .

+1

I know this is an old thread, but I came across this as one of the first search results from Google. I solved the problem by setting the static variable.

namespace Vert
{
   static int i;
}

I tried extern and in my situation, which did not seem to solve the problem.

+1
source

This binding error can also be fixed if variables included multiple times through "Variables.h" are declared as const.

0
source

All Articles