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?
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.
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.
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"
.
In addition, How to mix C and C++ has great tips about the topic.
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;
}