加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 通过来自另一个翻译单元的指针调用具有内部链接的函数

发布时间:2020-12-16 10:02:53 所属栏目:百科 来源:网络整理
导读:我们可以在匿名命名空间中声明一个回调函数(从而赋予它内部链接),知道它将从另一个翻译单元(甚至另一个库)调用吗? 一些lib: void register_callback(void (*cb)()){ .. cb(); ..} 主程序 namespace {int foo_cb() { ... } // internal linkage}int main(){
我们可以在匿名命名空间中声明一个回调函数(从而赋予它内部链接),知道它将从另一个翻译单元(甚至另一个库)调用吗?

一些lib:

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

主程序

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

int main()
{
   register_callback(foo_cb);
}

解决方法

TL; DR:是的,没关系

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

  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.
  2. […]

  3. 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

    • a function; or

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读