8

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 6

5

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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

5

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

2

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.

3 Comments

Why the downvote? It may not be the approach the OP prefers, but I don't see anything in the answer that's incorrect, or decidedly bad advice.
I guess not, but those of us who prefer C find the "just compile it as C++" solution all too quickly brought up, and then criticized for being C-style. Let the dwindling compatibility between the languages be what it is. The two languages are different and shouldn't pretend otherwise.
Your personal language preference should not be a reason to downvote answers that consider other languages to be superior.
0

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.

Comments

0

See also How to mix C and C++.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.