// call_cc.cpp calls a C program which calls back to this C++ program // must be compiled with call_cc.c or at least linked with // the object file from the C program extern "C" { // function prototype for a C function char call_c(int x, float y); } #include using namespace std; int main() { char c; int x=5; float y = 1.5; cout << "in C++ about to call a c: function, call_c" << endl; c = call_c(x, y); cout << "in C++: returned from call_c with " << c << endl; cout << "in C++: x = " << x << " y = " << y << endl; return 0; } extern "C" { // a C++ functiona callable be a C function #include // probably should use C rather than C++ char call_cc(int x, float y) { try // can use C++ in C callable function { // but must load C++ and C libraries cout << "in C++ extern \"C\" test that C++ allowed" << endl; } catch(...) {printf("some exception thrown in C++\n");} printf("in C++ called from c: x = %d, y = %g \n", x, y); return 'q'; } } // output of execution is: // in C++ about to call a c: function, call_c // in c: about to call a C++ function // in C++ extern "C" test that C++ allowed // in C++ called from c: x = 5, y = 1.5 // in c: returned from call_cc with q // in c: x = 5, y = 1.5 // in C++: returned from call_c with a // in C++: x = 5 y = 1.5