Yes it is possible. However, as BoBTFish says in the comment above, you (or the contractor) should develop a C interface for the C ++ library:
- write a header file that compiles in both C and C ++ and declares some
extern "C" functions. The interfaces of these functions must be valid in C, which in terms of C ++ means that they use only POD types (for example, without links) and do not throw exceptions. You can declare C ++ non-POD classes as incomplete types and use pointers for them, so usually every non-static member function is wrapped with a function that takes a pointer that becomes this as its first parameter. - implement functions in C ++ to call the C ++ library
- compile the library and shell as C ++
- compile your program as C (you can
#include header wherever necessary) - bind all this together with g ++ so that C ++ components can reference libstdC ++.
I suppose you can argue that since the program is connected with g ++, it is by definition a C ++ program that uses the C library (which contains main ), and not a C program that uses the C ++ library. Personally, I would not argue with this, it is important that none of the existing C-code does not change.
Example:
lib.h
#ifdef __cplusplus extern "C" #endif int foo();
lib.cpp
#include "lib.h" #include <vector> #include <iostream> int foo() { try { std::vector<int> v; v.push_back(1); v.push_back(1); std::cout << "C++ seems to exist\n"; return v.size(); } catch (...) { return -1; } }
main.c
#include "lib.h" #include <stdio.h> int main() { printf("%d\n", foo()); }
to build
g++ lib.cpp -c -olib.o gcc main.c -c -omain.o g++ main.o lib.o -omain
The following also works instead of the third line if you want to make an arbitrary distinction between using gcc for reference and using g++ :
gcc main.o lib.o -llibstdc++ -omain
However, I'm not sure that gcc -libstdc++ will work the same as g++ for all possible code that could be in lib.cpp . I just tested it for this example, and of course there is a lot of C ++ there that I haven't used.
Steve jessop
source share