Checking if a function has C-linkage at compile-time

Posted by scjohnno on Stack Overflow See other posts from Stack Overflow or by scjohnno
Published on 2010-05-29T19:40:17Z Indexed on 2010/05/29 19:42 UTC
Read the original article Hit count: 202

Filed under:
|
|

Is there any way to check if a given function is declared with C-linkage (that is, with extern "C") at compile-time?

I am developing a plugin system. Each plugin can supply factory functions to the plugin-loading code. However, this has to be done via name (and subsequent use of GetProcAddress or dlsym). This requires that the functions be declared with C-linkage so as to prevent name-mangling. It would be nice to be able to throw a compiler error if the referred-to function is declared with C++-linkage (as opposed to finding out at runtime when a function with that name does not exist).

Here's a simplified example of what I mean:

extern "C" void my_func()
{
}

void my_other_func()
{
}

// Replace this struct with one that actually works
template<typename T>
struct is_c_linkage
{
    static const bool value = true;
};

template<typename T>
void assertCLinkage(T *func)
{
    static_assert(is_c_linkage<T>::value, "Supplied function does not have C-linkage");
}

int main()
{
    assertCLinkage(my_func); // Should compile
    assertCLinkage(my_other_func); // Should NOT compile
}

Thanks.

© Stack Overflow or respective owner

Related posts about c++

Related posts about templates