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.
6 Answers
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.
Comments
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(); } Comments
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.
Comments
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.