I have this from C++ primer 5th edition: External Linkage:
If one function among a set of overloaded functions is a C function, the other functions must all be C++ functions:
class SmallInt { /* . . . */ }; class BigNum { /* . . . */ }; // the C function can be called from C and C++ programs // the C++ functions overload that function and are callable from C++ extern "C" double calc(double); extern SmallInt calc(const SmallInt&); extern BigNum calc(const BigNum&);
The C version of
calc
can be called from C programs and from C++ programs. The additional functions are C++ functions with class parameters that can be called only from C++ programs. The order of the declarations is not significant.
So what I understood from these declarations is that I can put them in a header. e.g:
// calc.h #ifdef __cplusplus class SmallInt { /* . . . */ }; class BigNum { /* . . . */ }; // C++ functions can be overloaded extern SmallInt calc(const SmallInt&); extern BigNum calc(const BigNum&); extern "C" #endif double calc(double); // C function
So do I need to define C version in a C source file and C++ version in a C++ source file?
// calc.c #include "calc.h" double calc(double){} // do_something // calc.cxx #include "calc.h" SmallInt calc(const SmallInt&){} // do_something BigNum calc(const BigNum&){} // do_something
Now I need to compile this way:
gcc print.c -c && g++ main.cxx print.cxx print.o -o prog
It works just fine but am I correct about my guesses and implementing this code?
What is the point in
extern
in the C++ versions (calc(const SmallInt&)
andcalc(const BigNum&)
) as long as they cannot be compiled with a C compiler? Thank you so much!