【问题标题】:change namespace variable value from outside (C++)从外部更改命名空间变量值(C++)
【发布时间】:2017-10-05 18:47:58
【问题描述】:

考虑以下命名空间:

// foo.h
namespace foo
{
    extern int bar;
}

//foo.cpp
namespace foo
{
    extern int bar = 42;
}

有没有办法在项目的其他地方(即不在命名空间内)更改 bar 的值?

我的意思是这样的:

// in some other .cpp file
#include foo.h

int setBar(int x)
{
    foo::bar = x;
}

【问题讨论】:

  • 为什么不呢?您是否尝试过并观察到其他东西?但是,您的 extern int bar = 42 令人不安。
  • 是的,语法与您显示的完全一样。这就提出了一个问题:你为什么要问?
  • 这是我在一个更大的项目中遇到的一些问题的一个非常简化的版本。我收到一个链接错误,上面写着:未解析的外部符号。它发生在我将代码更改为类似的东西之后......但也许我错过了其他东西:(
  • 唯一应该改变的部分是foo.cppbar 的定义应该是:int bar = 42;(提示:将extern 和初始化程序结合通常是错误的)。
  • 为什么在.CPP-文件中使用extern

标签: c++ namespaces extern


【解决方案1】:

有没有办法在项目的其他地方(即不在命名空间内)更改 bar 的值?

是的,almost exactly as you've shown。 示例代码中的唯一问题是您在定义foo::bar 变量的foo.cpp 文件中使用了extern。您需要从foo.cpp 中删除extern

#include <iostream>

// foo.h
namespace foo
{
    extern int bar; // use extern in header file to declare a variable
}

// foo.cpp
namespace foo
{
    int bar = 42; // no extern in cpp file.
}

int setBar(int x)
{
    std::cout << "old foo::bar: " << foo::bar << std::endl;
    foo::bar = x;
    std::cout << "new foo::bar: " << foo::bar << std::endl;
}

int main()
{
    setBar(999);
}

输出:

old foo::bar: 42
new foo::bar: 999

【讨论】:

  • 谢谢!所以我确实需要一些setBar 函数?我的意思是 - 在命名空间内?
  • @noamgot 不,这只是您的示例函数。在任何你想修改foo::bar 的地方你只需要声明它:namespace foo { extern int bar; }
【解决方案2】:

如果你声明一个变量为extern,那么你告诉编译器他不应该在当前的翻译单元中定义这个变量,而是让链接器在另一个翻译单元中寻找一个定义的变量。因此extern 只是声明了一个变量,但没有定义它。因此,初始化尚未定义的变量是没有意义的。

所以你实际上应该写:

// foo.h
namespace foo
{
    extern int bar; // Just declare...
}

//foo.cpp
namespace foo
{
    int bar = 42;  // Define and initialise
}

请注意,您仍然提供带有extern int bar 的头文件,当它被foo.cpp 以外的其他翻译单元包含时 - 声明变量bar 以便代码可以引用它,即使它是在另一个库中定义的(例如foo.o)。

【讨论】:

    猜你喜欢
    • 2011-05-11
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    相关资源
    最近更新 更多