Created
August 24, 2015 13:37
-
-
Save paulbuis/e47130c9e4e2a684ce65 to your computer and use it in GitHub Desktop.
Calling C++ from C
This file contains hidden or 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
using namespace std; | |
#include <iostream> | |
extern "C" void hello(int repeatCount) { | |
for (int i=0; i<repeatCount; i++) { | |
cout << "hello from C++" << endl; | |
} | |
} |
This file contains hidden or 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
#include "hello.h" | |
int main(int argc, char** argv) { | |
hello(3); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.