C++ – Advantages/Disadvantages of Compiling as Both C and C++

c

So I've seen some C libraries written so that they compile without any changes with a C++ compiler, for example Lua.

What are some advantages and disadvantages of doing this?

A few basic ones I see are:

Advantages:

  • library can be used with any C or C++ project with no extra effort (without using extern "C" for example).

Disadvantages:

  • Harder to maintain because you need it compile as both (involves things like extra casts which can hide bugs)
  • Either limit yourself to C/C++ (sacrificing things like flexible array members), or end up with non-standard C++.

But I'm sure there's more to consider than just the above advantages and disadvantages. What sort of cases would doing this be appropriate, instead of using either pure C or C++ for the library?

Best Answer

Well, there are many disadvantages:

  1. You cannot write good, idiomatic C, as it must also be valid C++.
  2. Dito for C++, but worse.
  3. Maintainers need to know C, and all the differences to C++. That is in effect a different third composite-language featuring the disadvantages of either plus all incompatibilities.
    I wonder if there is any good documentation for that? Especially as every combination of C version and C++ version is a different challenge.
  4. If you use multiple languages, you have to compile it as C and include it within a manually added extern "C"-block anyway.

Why not simply write it in whatever language you want, featuring a C-interface, and optionally adding a C++ facade on top of it for ease of use?

Related Topic