Re: Need to create a C lib - using C++ classes - is it possible
On May 25, 5:53 am, "Alf P. Steinbach" <al...@start.no> wrote:
* Angus:
We have a lot of C++ code. And we need to now create a
library which can be used from C and C++. Given that we
have a lot of C++ code using classes how can we 'hide' the
fact that it is C++ from C compilers?
The C++ code will need the C++ runtime library.
Good point. If you don't use any standard components from the
library, nor new, nor typeid, maybe not, but then what's the
point.
Within the standards of C and C++ the only way to achieve that
is to insist that the C code using the library is called from
a C++ main program.
No. There are two separate issues involved here. Neither the C
nor the C++ standards say anything about how the compiler is
invoked; to get the C++ library with gcc, for example, you can
either invoke it as g++, or specify the library explicitly
(-lstdc++, with the normal Unix linkers). Formally, the C++
standard requires that main() be written and compiled in C++, or
you have undefined behavior. (I'm not sure, but that could also
be the case in C.) In practice, the reason for this is to
ensure correct initialization of variables with static lifetime;
if you have no static variables, it's possible that you won't
have a problem (but don't forget that std::out, etc. are static
variables). And there too, the implementation could provide
other additional arrangements. (I'm not sure, but I think if
you compile with g++, rather than gcc, one of the effects is to
cause a different crt0 to be used, and that it is this crt0
which ensures the construction and destruction of static
variables. And it's also possible that some compilers add
special information to the object file when you compile a
program in C++, or perhaps only when you compile the program
with main, so that it will work. This trick can also be used to
ensure the additional libraries.)
In Windows an alternative is to have the library as a DLL,
because Windows DLLs are more decoupled.
That sort of works in Unix, as well, if the C++ standard library
is also a DLL. (Which is generally NOT recommended, of course.)
[...]
The best is to forget that silly idea. Using C library from
C++, OK. But C++ has additional requirements from runtime
library, so other way, generally !OK, unless you're working at
a low level where you wouldn't have to ask...
It's actually a frequent requirement, and the original posters
question reflects one of the more common ways of migrating to
C++.
--
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