Re: Need to create a C lib - using C++ classes - is it possible
On May 24, 10:41 pm, Ian Collins <ian-n...@hotmail.com> wrote:
sebastian wrote:
Just enclose the user code in the C linkage namespace, eg:
extern "C" {
// C code
}
Not a lot of use if the code is C and compiled with a C compiler...
In the header file, this has to be conditional, and only present
if the compiler is a C++ compiler. And of course, the library
source files must be compiled with the C++ compiler. The
classical solution is to use something like:
#ifdef __cplusplus
extern "C" {
#endif
// Usual contents here...
#ifdef __cplusplus
}
#endif
It's ugly, but it works.
Also, of course, you have to ensure that the "usual contents"
are all acceptable and mean the same thing to both the C and the
C++ compiler. You can freely use classes, for example
(including classes with virtual functions, et al.), but you
cannot define them in a header which will be used by the C code;
the most you can do is declare them, e.g.:
struct MyClass ;
, and because this results in an incomplete type, any use in the
header is restricted to pointers and the like.
Similarly, you can't use references in the interface exposed to
C.
One frequent solution is to define a class, exactly as one would
in C++, and then provide a set of wrapper functions, something
along the lines of:
#ifdef __cplusplus
extern "C" {
#endif
struct MyClass ;
MyClass* createMyClass(...) ;
void doSomethingWithMyClass( MyClass*, ... ) ;
// ...
#ifdef __cplusplus
}
#endif
The functions then just forward to the class members.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34