c++在命名空间中共享变量时出现重复符号链接器错误
对于 C++ 来说还是比较新的,
我有一个带有命名空间的头变量,其中有一些常量,看起来像这样
namespace blah {
const std::string x="foo";
}
我以这种方式访问变量没有问题 - dosomething(blah::x);等等。现在我想更改变量,以便可以修改它。如果我只是取出 const,我会收到链接器错误“重复符号 blah::x”。在这里添加 extern 没有帮助:
namespace blah {
extern std::string x;
}
它说默认情况下启用 extern,并且我得到相同的重复符号错误。这样做的正确方法是什么?
(在后一种情况下编辑,我还不想设置变量值。我想在其他地方导出它并共享该值。为了澄清 - 我想摆脱 const 这样我就可以更改值(例如使用当我摆脱 const 时,我得到了有关重复符号的错误。)
Still relatively new to C++
I have a header variable with a namespace with a few constants that looks something like this
namespace blah {
const std::string x="foo";
}
I have no problems accessing the variables this way - dosomething(blah::x); etc. Now I want to change the variable so it can be modified. If I just take out the const I get a linker error "duplicate symbol blah::x". Adding an extern here doesn't help:
namespace blah {
extern std::string x;
}
It says that extern is enabled by default and I get the same duplicate symbol error. Whats the right way to do this?
(EDIT in the latter case, I don't want to set the variable value yet. I want to derive it elsewhere and share the value. To clarify - I want to get rid of the const so I can change the value (e.g. using command line arguments. When I get rid of the const is when I get the errors about duplicate symbols.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在头文件中,您应该声明变量:
在源文件中,您应该定义它为:
现在将
blah.h
包含在您想要多少个文件。您不会看到任何重新定义错误。如果您想摆脱
const
(正如您在评论中所说),那么只需将其删除,就像我所做的那样。In the header file, you should declare the variable:
And in the source file, you should define it as:
Now include
blah.h
in as many file as you want. You wouldn't see any redefinition error.If you want to get rid of
const
(as you said in the comment), then simply remove it, as I did.在头文件中声明
extern
:code.h
...并在单个 CPP 文件中定义它...
code.cpp
Declare the
extern
in a header file:code.h
...and define it in a single CPP file...
code.cpp
创建一个声明您的 extern 的头文件:
然后创建一个包含定义的源文件:
这样定义就会在 lib 中编译一次(您将链接到该库),并且不会被定义多次(无论您在哪里包含标题)。
Create a header file that declares your extern:
Then create a source file that contains the definition:
This way the definition gets compiled once in a lib (which you will link with), and won't be defined multiple times (everywhere you include the header).