【发布时间】:2015-08-17 23:49:31
【问题描述】:
我发现了这个: How do I use extern to share variables between source files? 它的主要答案对我来说相当清楚。
但是我不明白为什么这会给我一个错误:
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:无法解析的外部符号“类 x::A const x::a”(?a@x@@3VA@1@B)
(视觉工作室 2013)
编译这两个文件没问题,如果我删除 const 关键字,或者如果我将 extern 语句移动到包含文件中,我可以构建并运行它。
感谢您的解释(不能相信编译器错误);)
【问题讨论】:
-
我对 C++ 不太熟悉,但我不认为
extern A const a;(in x.h) 和extern const A a ;(in main.cpp) 是一回事。 -
@ColonelThirtyTwo:为什么?