英文:
Extern variable define inside namespace LNK2001 Error
问题
我在C++ Visual Studio中遇到了与这些外部定义变量有关的问题。
我有一些大型数据表格,它们被编译到代码中,而不是被读取。它们是以下形式的.cpp文件:
Table.cpp
namespace EX{
const int Var_Length=31;
const double Var[31]={31个双精度数};
}
在同一个解决方案中,我有另一个class.h和class.cpp,我正在尝试在其中外部声明这些变量。
class.h
namespace EX{
class MyClass{};
extern const int Var_Length;
extern const double Var[];
}
我已经阅读了一堆帖子,但没有什么能够真正帮助。有些人建议它们可能需要成为全局变量。就C++语法而言,我还是相当新手,但我还没有看到任何涵盖命名空间外部变量的内容。
英文:
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.
答案1
得分: 2
常量变量具有内部链接。这意味着它们不能在它们被声明的编译单元之外引用。
你应该这样写:
namespace EX{
extern const int Var_Length = 31;
extern const double Var[31] = {31个双精度数};
}
根据C++ 17标准(6.5程序和链接):
3 具有命名空间范围(6.3.6)的名称如果是以下情况之一,它具有内部链接:
(3.2) — 非内联、非易失性、const限定类型的非内联变量,既未明确声明为extern,也未先前声明为具有外部链接;或者
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论