C Programming – Why Does C Provide Language Bindings Where C++ Falls Short?

bindingcportabilityprogramming-languages

I recently was wondering when to use C over C++, and vice versa? Fortunately someone already beat me to it and although it took a while, I was able to digest all the answers and comments to that question.

However one item in that post keeps being addressed again and again, without any kind of example, verification or explanation:

"C code is good for when you want to have multiple language bindings for your library"

That's a paraphrase. I should note that several people point out that multiple language bindings are possible in C++ (via some extern functioning), but nevertheless, if you read that post in its entirety, it's pretty obvious that C is ideal for portability/language binding. My question is: why?

Can someone please provide concrete reasons why writing libraries in C allows for easier bindings and/or portability in other languages?

Best Answer

C has a much, much simpler interface, and its rules for converting a source code interface into a binary interface are straightforward enough that generating external interfaces to bind to is done in a well-established manner. C++, on the other hand, has an incredibly complicated interface, and the rules for ABI binding are not standardized at all, neither formally nor in practice. This means that pretty much any compiler for any language for any platform can bind against an external C interface and know exactly what to expect, but for a C++ interface, it's essentially impossible because the rules change depending on which compiler, which version, and which platform the C++ code was built with.

In C, there's no standard binary language implementation rules, either, but it's an order of magnitude simpler and in practice compilers use the same rules. Another reason making C++ code hard to debug is the above-mentioned complicated grammar, since debuggers frequently can't deal with many language features (place breakpoints in templates, parse pointer casting commands in data display windows, etc.).

The lack of a standard ABI (application binary interface) has another consequence - it makes shipping C++ interfaces to other teams / customers impractical since the user code won't work unless it's compiled with the same tools and build options. We've already seen another source of this problem - the instability of binary interfaces due to the lack of compile time encapsulation.

-- Defective C++