【问题标题】:Why do I need an include file for extern variables?为什么我需要外部变量的包含文件?
【发布时间】: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:为什么?

标签: c++ extern


【解决方案1】:

命名空间范围const 变量默认为内部链接(即,仅在该翻译单元内可见)。需要extern 来覆盖默认值并为其提供外部链接(以便可以从不同的翻译单元访问它)。

【讨论】:

    猜你喜欢
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    相关资源
    最近更新 更多