1

I need to edit and access a few variables across multiple cpp files in a visual studio project. So I created a header file with a namespace containing all the variables I require as follows:

namespace windowdimension{
    TCHAR openwindows[20][180];
    int winnum = 0;
    int windowleft = 0;
    int windowright = 1360;
    INT windowtop = 0;
    INT windowbottom = 768;
    LONG leftarray[20];
    LONG rightarray[20];
    LONG toparray[20];
    LONG bottomarray[20];

}

However if I #include this header file in two source files, I get this linker error 2005 saying the parameter was already defined in the other obj.

On referring to other question of the same error, I got to know here that

a function definition can only appear once. Every .cpp file that #includes your .h file will generate yet another copy of the function.

But does that hold for namespace variables as well? If so how do we ensure access to a particular variable across multiple source files?

Community
  • 1
  • 1
annie1994
  • 143
  • 1
  • 6

2 Answers2

2

You should never define global variables in a header file.

To be able to share, you need to declare them in a header file (using extern keyword), and define only once in a .cpp file.

Sure, never forget about include guards in every header file (#pragma once is pretty portable solution):

global.hpp

#pragma once

namespace global {
   extern int variable;
}

global.cpp

namespace global {
   int variable = 0;
}

Anyway, it is a very bad practice to use global variables.

Stas
  • 11,571
  • 9
  • 40
  • 58
0

You probably forgot to add an include guard:

Header.h

#ifndef HEADER_H
#define HEADER_H

namespace something {
}

#endif

Another option is to use #pragma once in the very beginning of your header file.

Community
  • 1
  • 1
ForceBru
  • 43,482
  • 10
  • 63
  • 98