为什么我需要一个包含文件的外部变量
Why do I need an include file for extern variables?
我发现了这个:如何使用extern在源文件之间共享变量?它的主要答案对我来说很清楚。
然而,我不明白为什么这会给我一个错误:
x.h:
#pragma once
namespace x {
class A {
public: void func() const;
};
// extern A const a; // cannot move this out of the include file !!!
// extern int xi; // fine to remove from here
}
——main.cpp——
#include "stdafx.h"
#include "x.h"
namespace x { extern int xi; extern const A a ; } // instead of include file
extern int i;
int _tmain(int argc, _TCHAR* argv[])
{
std::cout << i << std::endl; // works
std::cout << x::xi << std::endl; // works
x::a.func();
return 0;
}
——x.cpp——
#include "stdafx.h"
#include "x.h"
namespace x
{
void A::func() const
{ std::cout << "x::A::func() called" << std::endl; }
const A a; // Problem if const
int xi = 234; // works
}
int i = 123; // works
错误LNK2001:无法解析的外部符号"class x::A const x::A " (?a@x@@3VA@1@B)
(VisualStudio 2013)编译这两个文件很好,如果删除const关键字,或者将extern语句移到include文件中,就可以构建并运行它。
谢谢你的解释(不能相信编译器的bug);)
名称空间范围const
变量默认为内部链接(即,仅在该翻译单元中可见)。需要extern
来覆盖默认值并为其提供外部链接(以便可以从不同的翻译单元访问它)。
相关文章:
- C++-字符串是否包含一个带有简单循环的单词
- 如何在 c++ 项目中包含一个包含所有头文件?
- 计算在同一位置至少包含一个常用字符的不同字符串对
- 在使用PyInstaller冻结Python脚本时包含一个C++可执行文件
- 只要我不包含一个标题,重新定义C++关键字合法吗
- 我该如何循环遍历我的数组(缓冲区——包含一个文本文件),并将其打印成30字节的块
- 为什么我应该在scanf()-家族成员中包含一个长度修饰符作为参数?有什么好处?使用长度修改器进行扫描的作用
- 重载运算符主体仅包含一个函数调用
- 一次包含一个 #include 表达式的多个头文件?
- C++:如何创建一个临时对象,包含一个指针 - 常量或非常量,具体取决于上下文
- 如何查找一组类型对是否包含一个元素作为第二个成员
- 仅包含一个 printf 的程序崩溃
- NDK - 包含一个预构建的库,并在 Android 项目中调用本机函数
- 如何为字符串编写正则表达式,其中包含一个数字至少一个数字,并且不包含任何字母
- 如何在Java中包含一个库,该库在C 中具有Java中具有本机绑定(库)的库
- 为什么string.empty()在字符串包含一个值时评估为true
- [C ] NULL确实在内存中也包含一个特定的地址
- 如果QString包含一个数字
- 为什么 C++11 包含一个关于比较空指针的奇怪子句
- 正在(在构造函数中)将其包含一个不良设计的指针传递,如果是的,则解决方案是什么