Created
May 17, 2013 15:43
-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(×2, argc); | |
assert(a == b); | |
return a; | |
} |
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
That should work as expected.
There is no undefined behavior in this code.