1

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.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
JAM1693
  • 33
  • 4

1 Answers1

2

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    This language construct has not changed much over the years, so we would be amiss to not mention the canonical Q&A on extern. https://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files – Captain Giraffe Mar 03 '23 at 22:09
  • Thanks very much for the explanation. I suspected it had to do with the const type but I had not seen an example like this. This works. Kicking myself for not figuring that out! – JAM1693 Mar 03 '23 at 23:58