gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:10:45 24 4
gpt4 key购买 nike

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

一些库:

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

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

关于c++ - 通过来自另一个翻译单元的指针调用具有内部链接的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37442606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com