Reputation: 8487
Just out of curiosity: Is there a way to use C++ files in C projects? With files I mean the ability to access functions from header files and libraries and use them in your own projects for problems that have already been solved.
Upvotes: 8
Views: 4910
Reputation: 3638
If you provide a C API for the C++ library, then you can use it. Simply define the C API in a separate header (you can't use headers with C++ code in C files). The ICU project does just this, it uses C++ internally, but provides both C and C++ APIs.
Upvotes: 0
Reputation: 248269
Is it an option to go the opposite way? C++ code can include C headers and link to C libraries directly (and C code can usually be compiled as C++ with few or no changes), but using C++ from C requires a bit more care.
You can't include a C++ header from a C file and expect to compile it as C.
So what you'll have to do is expose a C-compatible interface from your C++ code (a header where everything is wrapped in extern "C"
, and which uses no C++-specific features). If you have such a header, you can simply include it from your C code, and link to the C++ library.
Upvotes: 5
Reputation: 12393
If you externalize your functions, variables and struct with
extern "C" {
int global;
}
in the header-files and with
extern "C" int global = 20;
in your C++ code, it will be usable from C-code. The same rule applies to functions.
You can even call methods with appropriate prototypes. E.g:
class C
{
public:
c(int);
int get();
};
The C-Wrapper in your .cpp could look like:
extern "C" void * createC(int i)
{
return (void *) new C(i);
}
extern "C" int Cget(void *o)
{
return ((C *)o)->get();
}
Upvotes: 5
Reputation: 5552
Probably the simplest thing to do is to just compile your C files with a C++ compiler. The vast majority of the code will be compatible, and you'll get the ability to use C++ headers for free.
Upvotes: 2
Reputation: 272762
Yes, it is possible to mix C and C++ if you're careful. The specifics will depend on what compiler, etc. you're using.
There's a whole chapter about it at the C++ FAQ: http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html.
Upvotes: 5