Skip to content

Instantly share code, notes, and snippets.

Created May 17, 2013 15:43
Show Gist options
  • Save anonymous/5599924 to your computer and use it in GitHub Desktop.
Save anonymous/5599924 to your computer and use it in GitHub Desktop.
Test program to see what compilers enforce C and C++ having different function pointer types (and different calling conventions).
// What systems does this break on?
// The C++ standard says that function pointers to C and C++ functions are
// different types even if they have the same signature.
#include <assert.h>
extern "C" int run(int (*f)(int), int x) { return f(x); }
int times2(int x) { return x * 2; }
int main(int argc, char *argv[]) {
int a = times2(argc);
// This is undefined behavior according to C because I am passing an
// "extern C++" function pointer to an "extern C" function.
int b = run(&times2, argc);
assert(a == b);
return a;
}
Copy link

ghost commented May 17, 2013

That should work as expected.
There is no undefined behavior in this code.

Copy link

ghost commented May 17, 2013

In this code the function run() is compiled by the C++ compiler.
So even though its ABI is C it can still call C++ functions (even through a function pointer). In fact the code planted is going to call a C++ function as the parameter f is not declared to have extern "C" interface. Thus it is expecting f to point at a C++ function and will plant the appropriate code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment