How common is it to mix C with C++?

163 Views Asked by At

I wanted to know how widely used is the mixing of C++ and C. I mean as in using of C libraries/functions and call it in C++ program like how it is done here Mix C with C++. How extensive is its use in real world? Is it rarely used, avoided mostly or pretty common? Anybody can shed some lights on it??

1

There are 1 best solutions below

5
On BEST ANSWER

It is fairly common. You can either

or

  • use both object files, static and dynamic libraries compiled with C compiler but then you should be aware of name mangling that C++ compiler does and the C compiler does not (due to the fact that C does not allow name overloading but C++ does). In such case there is extern "C" linker directive to use C linkage, i.e. does not mangle names that has been compiled with C compiler.

For good explanation how to use C linkage in C++, refer e.g. to this answer here on SO: https://stackoverflow.com/a/1041880/12118546

This is the reason you often see code like this

#ifdef __cplusplus
extern "C" {
#endif

// all of your legacy C code here

#ifdef __cplusplus
}
#endif

Sample from: https://stackoverflow.com/a/12994075/12118546

Cryptic linker errors like these would result if you would forget about this:

...
/home/AbiSfw/ccvvuHoX.o: In function `main':
prog.cpp:(.text+0x19): undefined reference to `foo()'
...

Sample from: https://stackoverflow.com/a/12573818/12118546