Skip to content

Instantly share code, notes, and snippets.

@paulbuis
Created August 24, 2015 13:37
Show Gist options
  • Save paulbuis/e47130c9e4e2a684ce65 to your computer and use it in GitHub Desktop.
Save paulbuis/e47130c9e4e2a684ce65 to your computer and use it in GitHub Desktop.
Calling C++ from C
using namespace std;
#include <iostream>
extern "C" void hello(int repeatCount) {
for (int i=0; i<repeatCount; i++) {
cout << "hello from C++" << endl;
}
}
#include "hello.h"
int main(int argc, char** argv) {
hello(3);
}
@paulbuis
Copy link
Author

To be callable by C, the C++ function needs to be declared as extern "C" to prevent name mangling.

Note that without name mangling, C not only can't support function overloading (two or more functions with same name but different argument types), but if the convention of putting function prototypes in header files that are checked against both points of use and point of definition isn't followed, there is no way to make sure types match. K&R C didn't provide for prototypes, but the later ANSI C required them at point of use. However, even with ANSI C, different prototypes might be provided in different files if convention of putting prototypes in a single header file is not followed.

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