多重定义和命名空间
这是在命名空间中包含函数的正确方法吗?我将在多个文件中 #include 函数?
测试.h
#pragma once
#ifndef TEST
#define TEST
namespace test{
namespace {
bool test(){
return true;
}
}
}
#endif //TEST
Is that the right way to have functions in namespace that i will #include in multiple files?
test.h
#pragma once
#ifndef TEST
#define TEST
namespace test{
namespace {
bool test(){
return true;
}
}
}
#endif //TEST
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
包含保护名称
TEST
可能与其他一些宏冲突,请使用更复杂的名称,例如HEADERNAME_H
。注意:以下划线开头后跟大写的名称以及包含两个连续下划线的名称保留用于实现。
其次,如果您要将其放入头文件中,则函数定义需要内联
。否则,当包含在多个翻译单元中时,您将收到多个定义链接器错误。或者更正式地说,该标准的 ODR(单一定义规则)禁止此类多个定义,除非它们都是内联
并且实际上相同。编辑:删除上面的内容,因为我没有看到您使用匿名命名空间。
不使用匿名命名空间,它在每个翻译单元中为您提供单独的命名空间,并在每个此类命名空间中提供单独(相同)的函数定义,而不是仅使用
inline
- 如删除文本中所述多于。干杯&呵呵,
The include guard name
TEST
is likely to conflict with some other macro, use something more elaborate, likeHEADERNAME_H
.Note: names that start with underscore followed by uppercase, and names that contain two successive underscores, are reserved for the implementation.
Secondly, if you're going to put that in a header file, then the function definition needs to beinline
. Otherwise, when included in multiple translation units you'll get a multiple definition linker error. Or more formally, the standard's ODR (One Definition Rule) forbids such multiple definitions, unless they're allinline
and effectively identical.Edit: delete above because I didn't see your use of an anonymous namespace.
Instead of the anonymous namespace, which gives you a separate namespace in each translation unit and a separate (identical) function definition in each such namespace, instead of that just use
inline
– as explained in striked-out text above.Cheers & hth.,
匿名命名空间使它们包装的所有标识符对于它们所在的翻译单元来说是唯一的。将匿名命名空间放入将(迟早)包含在不同翻译单元中的标头中将导致该匿名命名空间中定义的所有标识符在每个翻译单元中单独(但相同)。
我还没有看到有人想要这个的用例。
Anonymous namespaces make all identifiers they wrap unique to the translation unit they are in. Putting an anonymous namespace into a header that will (sooner or later) be included in different translation units will result in all the identifiers defined in that anonymous namespace to be separately (but identically) in each translation unit.
I have yet to see a use case where one wants this.
是的。因为它使您能够用相同的名称命名相同的事物并保持名称简单
Yes. Because it give you an ability to name the same things with same names and keep this names simple