views:

211

answers:

5

I am writing a program in C, but I would like to use dynamic libraries like a vector. Is it possible to use C++ libraries in a C program?

+1  A: 

Yes, as long as you compile it using a C++ compiler. Note that this no longer makes it a C program, but a C++ program.

Evän Vrooksövich
+1  A: 

You can if your compiler compiles C++. I'd say in most compiler cases you can especially if you are using gcc.

Most IDE's let you create a new C++ application which you can then write code in plain C and use C++ objects when you want to.

You can do this because C++ is a superset of C. Which means that C++ includes all of C's features and adds more functionality on top of C.

Brock Woolf
+1  A: 

std::vector is a template class. It relies on the special syntax C++ provides to exist.

You may be able to wrap its functionality with a collection of functions that pass around an opaque pointer to a vector, at the cost of handling allocation of the vector class yourself.

I'd suggest against it, because you'll introduce needless complexity with questionable benefit. Just write C++ when you need to use C++ constructs, and abstract that behind functions declared extern "C".

greyfade
+2  A: 

In addition, How to mix C and C++ has great tips about the topic.

Moayad Mardini
+8  A: 

Not std::vector, no. Anything templated is right out.

In general it's un-fun to use C++ code, but it can be done. You have to wrap classes in plain non-class functions that your C code can call, since C doesn't do classes. To make these functions useable from C you then wrap them with an extern "C" declaration to tell the C++ compiler not to do name mangling.

You can then compile the wrapper functions with a C++ compiler and create a library which your C program can link against. Here's a very simple example:

// cout.cpp - Compile this with a C++ compiler
#include <iostream>

extern "C" {
    void print_cout(const char *str) {
        std::cout << str << std::endl;
    }
}

/* print.c - Compile this with a C compiler */
void print_cout(const char *);

int main(void) {
    print_cout("hello world!");
    return 0;
}
John Kugelman
Then you need to link the c++ library to the application i assume. For example by doing the final linking with g++ instead of gcc. I assume that was ovious.
elcuco
John answer's is good. But linking together C++ and C code can be difficult.I recommend using Dynamic Libraries here (.so or .dll)
toto