通过另一个翻译单元的指针调用具有内部链接的函数 [英] Calling a function with internal linkage via pointer from another translation unit

查看:65
本文介绍了通过另一个翻译单元的指针调用具有内部链接的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们是否可以在匿名命名空间中声明一个回调函数(从而为它提供内部链接),而又知道它会从另一个翻译单元(甚至是另一个库)被调用?

Can we declare a callback function in an anonymous namespace (thus giving it internal linkage), knowing that it will be called from another translation unit (another library even)?

某些lib:

void register_callback(void (*cb)())
{
  ..
  cb();
  ..
}

主程序

namespace {
int foo_cb() { ... } // internal linkage
}

int main()
{
   register_callback(foo_cb);
}


推荐答案

TL; DR:是的,没关系

TL;DR: yes, it is ok

来自[basic.link](强调我的):

From [basic.link] (emphasis mine):



  1. 一个名字被称为具有链接可能将同一个对象,
    引用,函数,类型,模板,名称空间或值表示为在另一个作用域中的声明引入的名称

  1. A name is said to have linkage when it might denote the same object, reference, function, type, template, namespace or value as a name introduced by a declaration in another scope:


  • 当名称具有内部链接时,表示的实体可以是
    ,由同一翻译中的其他范围按名称引用

  • When a name has internal linkage , the entity it denotes can be referred to by names from other scopes in the same translation unit.

[...]

未命名的名称空间或[...]具有内部链接。 [...]。如果上面的内部链接给出的名称空间范围不是
,则该名称与封闭的
名称空间具有相同的链接,如果它是

An unnamed namespace or [...] has internal linkage. [...]. A name having namespace scope that has not been given internal linkage above has the same linkage as the enclosing namespace if it is the name of

    的名称
  • 一个函数;或


所以基本上链接名称的属性,而不是对象,函数等的属性。这意味着在未命名空间中声明的函数不能从另一个翻译单元通过名称调用。没有指针可以调用它的限制。

So basically linkage is a property of names rather than of objects, functions etc. This means that a function declared inside an unnamed namespace cannot be called by name from another translation unit. There is no restriction to call it by it's pointer.

这篇关于通过另一个翻译单元的指针调用具有内部链接的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆