I'm working with a contractor who develops a library for us in C++. I would like to know if it is possible to use that library in a C program. I am using Gcc as my compiler.
Yes, it is possible. However, as BoBTFish says in a comment above, you (or the contractor) must design a C interface for the C++ library:
extern "C"
functions. The interfaces of these functions must be valid in C, which in C++ terms means they use only POD types (for example no references) and don't throw exceptions. You can declare non-POD C++ classes as incomplete types and use pointers to them, so commonly each non-static member function is wrapped by a function that takes the pointer that will become this
as its first parameter.#include
the header wherever needed)I suppose you might argue that since the program is linked with g++, it's by definition a C++ program that uses a C library (that happens to contain main
) rather than a C program that uses a C++ library. Personally I wouldn't bother arguing that, the important point is that none of your existing C code changes.
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());
}
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 do want to make an arbitrary distinction between using gcc
to link and using g++
:
gcc main.o lib.o -llibstdc++ -omain
However, I am not certain that gcc -libstdc++
will work as well as g++
for all possible code that could be in lib.cpp
. I just tested it for this example, and of course there's a lot of C++ that I haven't used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With