C++ 从外部更改命名空间变量值(C+;+;)
考虑以下名称空间:C++ 从外部更改命名空间变量值(C+;+;),c++,namespaces,extern,C++,Namespaces,Extern,考虑以下名称空间: // 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; } 是否有办法在项目中的其他地方
// 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;
}
是否有办法在项目中的其他地方(即,不在名称空间内)更改bar的值
对。
示例代码中唯一的问题是,在定义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);
}
如果您将一个变量声明为
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
中)定义,代码也可以引用它。为什么不?你有没有试过并观察到别的东西?但是,您的extern int bar=42
令人不安。是的,语法与您所显示的完全相同。这就引出了一个问题:你为什么问这个问题?这是我在一个更大的项目中遇到的一些问题的一个非常简化的版本。我得到一个链接错误,上面写着:未解析的外部符号。它发生在我将代码更改为类似的内容之后。。。但也许我遗漏了其他一些东西:(唯一应该改变的部分是foo.cpp
中bar
的定义应该是:int bar=42;
(提示:将extern
与初始值设定项组合通常是错误的)。为什么要在.CPP
-文件中使用extern
?谢谢!所以我确实需要一些setBar
函数?我的意思是-在名称空间内?@noamgot不,这只是您的示例函数。如果您想修改foo::bar
只需声明它:名称空间foo{extern int bar;}
// foo.h
namespace foo
{
extern int bar; // Just declare...
}
//foo.cpp
namespace foo
{
int bar = 42; // Define and initialise
}