为什么我需要一个包含文件的外部变量

Why do I need an include file for extern variables?

本文关键字:包含 一个 文件 变量 外部 为什么      更新时间:2023-10-16

我发现了这个:如何使用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来覆盖默认值并为其提供外部链接(以便可以从不同的翻译单元访问它)。

相关文章: