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

Calling a function with internal linkage via pointer from another translation unit

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

一些库:

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

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