Using C ++ files in a C project

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 resolved.

+7
source share
6 answers

Yes, you can mix C and C ++ if you are careful. The specifics will depend on which compiler, etc. You are using.

There is a whole chapter about this in the C ++ FAQ: http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html .

+5
source

If you are externalizing your functions, variables and struct with

extern "C" { int global; } 

in the header files and

 extern "C" int global = 20; 

in your C ++ code, it will be used from C code. The same rule applies to functions.

You can even call methods with appropriate prototypes. For example:

 class C { public: c(int); int get(); }; 

C-Wrapper in your .cpp might look like this:

 extern "C" void * createC(int i) { return (void *) new C(i); } extern "C" int Cget(void *o) { return ((C *)o)->get(); } 
+5
source

Is it possible to go the other way around? C ++ code can include C headers and a link to C libraries directly (and C code can usually be compiled as C ++ with little or no change), but using C ++ with C requires a bit more caution.

You cannot include the C ++ header from a C file and expect to compile it as C.

So you will need to make a C-compatible interface from your C ++ code (a header where everything is wrapped in extern "C" , and which does not use any C ++-specific functions). If you have such a header, you can simply include it from your C code and a link to the C ++ library.

+4
source

Probably the easiest thing is to simply compile your C files using the C ++ compiler. The vast majority of code will be compatible, and you can use C ++ headers for free.

+1
source

If you provide the C API for the C ++ library, you can use it. Just define the C API in a separate header (you cannot use headers with C ++ code in C files). The ICU project does just that, it uses C ++ internally, but provides both C and C ++ APIs.

0
source
0
source

All Articles