kk****@yahoo.com wrote:
Hi. I need to write a C++ callback function and register it with a C
program. I've read that this can be done if the callback function is a
static method. I've also read that I should use a global function with
the extern "C" prefix. I was leaning toward using the static method
approach until I saw a posting that said compatibility between static
C++ functions and C is not guaranteed in the respective language
standards. This made me start to favor the extern C approach.
Well, basically, none of them is really guaranteed. After all, the C++
standard doesn't require a C compiler to exist at all. However, often, the
C and C++ compilers are bundled together or made compatible. In that case,
a global extern "C" function is indeed the best choice. The thing is that
it selects "C" linkage, which is supposed to be the same linkage as the C
compiler uses. "Linkage" not only includes the functions internal symbol
names, but also the calling conventions, like how arguments are passed, who
cleans up the stack and so on. Those might be different in the C and C++
compilers, so their linkages could be incompatible.
The bottom line is that in many (probably most) compilers, it will work
either way, but the extern "C" approach is a bit more safe.