具有内部链接的内联函数?
在 C 中:为什么只有具有内部链接(即用静态声明)的内联函数可以引用(即复制地址、读取、写入或调用)具有静态存储持续时间的文件范围内的变量或函数,而其他内联函数则不能?
In C: Why is so that only inline functions with internal linkage (ie declared with static) may reference (ie copy address, read, write, or call) a variable or function at file scope with static storage duration while other inline functions may not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是事物的定义方式。
内联函数将被插入到调用它的模块中。因此,它无法访问定义它的模块中的私有内容。
如果内联函数仅在该模块中使用(内部链接)。然后就可以安全地授予它对该模块的“私有”内容的访问权限。
This is how things are defined.
The inlined function would be inserted in the module where it is called. So, it can't access the private stuff in its module where it is defined.
If the inlined function is only used in that module(internal linkage). Then it is safe to grant it an access to the "private" stuff of that module.
使用存储说明符“static”声明的具有文件范围的对象或函数具有内部链接。虽然其生命周期是程序的整个执行过程,但具有内部链接的对象不会为其他翻译单元声明(即从其他翻译单元可见)。
对于具有外部链接的内联函数,编译器可以:
在最后两种情况下,具有内部链接的对象将不可见。因此,具有外部链接的内联函数无法引用具有内部链接的标识符。
此外,它“不应包含具有静态存储持续时间的可修改对象的定义”,因为这可能会导致该对象的多个实例,这可能不是预期的行为。
An object or function with file scope, declared with the storage specifier "static" has internal linkage. While its lifetime is the entire execution of the program, a object with internal linkage is not declared for (i.e visible from) other translation units.
For an inline function with external linkage, the compiler may:
In the last two cases, objects with internal linkage would not be visible. Therefore an inline function with external linkage cannot reference an identifier with internal linkage.
Furthermore, it "shall not contain a definition of a modifiable object with static storage duration" as this could result in multiple instances of that object which is probably not the intended behavior.