从外部更改名称空间变量值 (C++)
change namespace variable value from outside (C++)
考虑以下命名空间:
// 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;
}
is there a way to change the value of bar somewhere else in the project (i.e, not inside the namespace)?
是的,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
如果你声明一个变量为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
中)。
考虑以下命名空间:
// 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;
}
is there a way to change the value of bar somewhere else in the project (i.e, not inside the namespace)?
是的,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
如果你声明一个变量为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
中)。