简体   繁体   English

为什么匿名名称空间中的函数/对象具有外部链接?

[英]Why do functions/objects inside anonymous namespace have external linkage?

Why don't symbols (functions and variables) that are defined in an anonymous namespace have internal linkage as with static keyword? 为什么在匿名名称空间中定义的符号(函数和变量)不像static关键字那样具有内部链接? If a function is not visible/accessible outside, what is the reason to have external linkage? 如果某个功能在外部不可见/不可访问,那么建立外部链接的原因是什么?

In C++03, names with internal linkage were forbidden from being used as template arguments[*]. 在C ++ 03中,禁止将内部链接的名称用作模板参数[*]。 So, names of most things in unnamed namespaces had external linkage to allow their use with templates. 因此,未命名名称空间中大多数事物的名称具有外部链接,以允许它们与模板一起使用。 You could explicitly give a name internal linkage in an unnamed namespace by declaring it static , same as in a named or global namespace. 您可以通过将其声明为static来显式地在未命名的命名空间中提供名称内部链接,这与命名或全局命名空间相同。

Both things changed in C++11 -- names in unnamed namespaces have internal linkage by default (3.5/4), and names with internal linkage can be used as template arguments. 两者都在C ++ 11中发生了变化-未命名的名称空间中的名称默认情况下具有内部链接(3.5 / 4),具有内部链接的名称可用作模板参数。

[*] for types, it must have external linkage. [*]对于类型,它必须具有外部链接。 For objects and functions, it must have external linkage if its address is used as a template argument, although it's OK for example to use as a template argument the value of a const integer with internal linkage. 对于对象和函数,如果将其地址用作模板参数,则必须具有外部链接,尽管例如可以将具有内部链接的const整数的用作模板参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM