Using C and C++ functions in the same program - how to do it
Archive - Originally posted on "The Horse's Mouth" - 2010-11-24 20:15:38 - Graham EllisIf you have some native C functions that you want to include in your C++, can you do so? The answer is a - slightly reserved - yes.
Firstly, you need to have your main program in C++ rather than being one of the C elements. Then you need both the C and C++ compilers to be from the same family / vendor and the same release, in order to avoid the combined code trying to call in two completely different sets of libraries. And finally you need to declare that the C functions actually are to be treated as C rather than as C++ at function prototype time.
I included an example, showing these, on an example on the course that finished earlier today ... you can see the C++ calling program [here] - and note the prototype:
extern "C" int avg(int, int);
although there's nothing special about the call to the function itself:
int num = avg(8, 24);
The C function is [here] ... and here's the compile, build sequence:
wizard:antrim graham$ gcc -c ave.c
wizard:antrim graham$ g++ -o Ns Ns.cpp ave.o
wizard:antrim graham$
This mixing of languages is a subject that comes up - occasionally - with many languages; you'll find me looking at it on Python, Lua and Tcl courses too, but only very briefly, and on public courses I'll only pull up examples "as required". The rule about the same family of compilers for the two languages (or for the compiler in the case of a scripting language) applies universally to avoid issues with multiple library loads and conflicts, and there's often issues with members being renamed with something like an extra underscore, or being "mangled" in order to avoid name conflicts across the various elements at load time.