Search code examples
c++callbackfunction-pointerslinkage

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


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)?

Some lib:

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

Main program

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

int main()
{
   register_callback(foo_cb);
}

Solution

  • TL;DR: yes, it is ok


    From [basic.link] (emphasis mine):

    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

    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.