c++namespacesexternlinkagelnk2001

Extern variable define inside namespace LNK2001 Error


I have been running into issues with these externally defined variables in C++ Visual Studio.

I have large data tables that are being compiled into code, rather than read. They are .cpp files defined as follows:

Table.cpp

namespace EX{
const int Var_Length=31;
const double Var[31]={31 Doubles};
}

In my same solution I have another class.h & class.cpp where I am trying to declare those variables externally.

class.h

namespace EX{
class MyClass{};
extern const int Var_Length;
extern const double Var[];
}

I have read through a bunch of posts but not have quite helped. Some suggest that they may need to be a global variable. I’m still quite a novice as far as C++ syntax goes but I haven’t seen anything that covers namespace external variables.


Solution

  • Constant variables have internal linkage. That is they can not be referred outside the compilation unit where they are declared.

    You should write

    namespace EX{
        extern const int Var_Length=31;
        extern const double Var[31]={31 Doubles};
    }
    

    From the C++ 17 Standard (6.5 Program and linkage)

    3 A name having namespace scope (6.3.6) has internal linkage if it is the name of

    (3.2) — a non-inline variable of non-volatile const-qualified type that is neither explicitly declared extern nor previously declared to have external linkage; or