Skip to content

Instantly share code, notes, and snippets.

@paulbuis
Created August 24, 2015 13:33
Show Gist options
  • Save paulbuis/5b29e463bc4e65e603d3 to your computer and use it in GitHub Desktop.
Save paulbuis/5b29e463bc4e65e603d3 to your computer and use it in GitHub Desktop.
Calling C from C++
#include <stdio.h>
#include "hello.h"
void hello(int repeatCount) {
int i;
for (i = 0; i < repeatCount; i++) {
printf("hello from C\n");
}
}
extern "C" void hello(int repeatCount);
int main(int argc, char** argv) {
hello(3);
}
@paulbuis
Copy link
Author

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.

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