0

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??

6
  • 7
    Technically its ubiquitous. Both Windows and *nix use a C API for interacting with the OS. Commented Aug 19, 2021 at 16:29
  • 5
    A significant number of libraries is written in C. You don't want to miss on them to maintain the "C++ purity". Commented Aug 19, 2021 at 16:29
  • Implementations of the C++ standard library itself will often mix C libraries. It's not required, but it's a fairly easy way to implement "things from C". Commented Aug 19, 2021 at 16:32
  • 1
    Even when writing mostly C++ projects (targeting windows) I very often have at least a few C files, mostly tool generated but not always. Commented Aug 19, 2021 at 16:45
  • If I am not wrong, pretty much the whole Arduino/microcontroller programming situation is like that Commented Aug 19, 2021 at 17:08

1 Answer 1

0

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

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

5 Comments

You're likely to get quite a few compilation errors when compiling C code as C++, unless the C code was written with this in mind. It's rare to do this in my experience.
compile the C stuff with C++ compiler without any issues This is bound to end in tears.
@interjay Those would be linker error, but I am not going to be a nitpicker here. I will add that to my answer as I was quite a confused when I have seen those for the first time.
I'm talking about compiler errors, not linker errors. See stackoverflow.com/questions/861517/…
Yay, I see now... Allright, adding these notes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.