Created
August 24, 2015 13:33
-
-
Save paulbuis/5b29e463bc4e65e603d3 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
#include <stdio.h> | |
#include "hello.h" | |
void hello(int repeatCount) { | |
int i; | |
for (i = 0; i < repeatCount; i++) { | |
printf("hello from C\n"); | |
} | |
} |
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
extern "C" void hello(int repeatCount); | |
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
In order to make the C function callable from C++, the C++ code needed to have a prototype where the function was marked as "extern C" to prevent name mangling. Normally, a C++ function's name would be mangled by the compiler to encode the return type and the argument types, allowing unique names at the assembly code level while allowing the same name to be overloaded at the source code level.