Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to include C++ libraries in C programs?

Tags:

c++

c

gcc

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.

like image 733
hephaestuz Avatar asked Dec 02 '13 09:12

hephaestuz


1 Answers

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:

  • write a header file that compiles in both C and C++, and that declares some 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.
  • implement the functions in C++ to call the C++ library
  • compile the library and the wrapper as C++
  • compile your program as C (you can #include the header wherever needed)
  • link it all together with g++ so that the C++ components can link against libstdc++.

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.

like image 56
Steve Jessop Avatar answered Oct 26 '22 16:10

Steve Jessop