Kaz Kylheku said:
I'm working on a program that can be built either with a C or C++ compiler.
Most of the time I forget about this, losing my awareness of "this has to be
valid C++ too", and I neglect to build it as C++ for weeks or months.
[...]
Out of curiosity, why are you doing this? What advantage do you gain
by writing code that can compile in either language?
I can write in a "better C", which is safer, but still compiles with C
compilers.
Conversely,
what would you lose by not worrying at all about C++ compatibility
(go ahead and call that variable "class" if you like)?
One example would be that I can't build the code any more with C++ to check
that all external names are meeting type-safe linkage and the one-definition
rule.
In C, I can have "extern int x;" in in one module, and "struct foo x = { 0 };"
in another. It will link.
If you change a C program such that a function has different parameters, but
due to some broken dependencies in your build system, some dependent modules
are not recompiled, you will get a broken link. Of course, it goes away
if you do a complete rebuild, but you could waste time chasing a bug
which isn't there.
This is fixed in C++: it will catch your broken build system. Type
safe linkage won't let an int (int, char *) call go to an
int (int, char *, char *) function.
(Ironically, I had such a problem recently and didn't catch it because
I had the project configured for the C compiler!)
The real question is, why not break away from C compatibility
and just use arbitrary C++?
That's the real reason for doing this: portability. I believe that C compilers
are still more widely available. Also more widely installed. If we look at just
GNU/Linux systems, g++ will never be present without gcc. But gcc will be
present without g++.
By the way, coding this way may come upon you as a feature request
from users! Years ago I developed that Kazlib library and I made sure
the headers were squeaky clean for C++ use.
But what did some people do? They took the .c files into their C++ projects and
compiled them as C++. So I got e-mails like, "hey your code breaks C++,
can we patch it".
This is probably one niche area where you need to write
in this common dialect: whitebox-reuse libraries that can be dropped
into C or C++ projects.
That's probably when I became more receptive to the idea that hey;
you can write C and C++ at the same time.
My impression is that the actual need for this is much rarer than
many people seem to think it is. (I do not include you in those
"many people").
It's usually not a need, but an easily obtained "nice to have".
You won't see this done very often not because it is awkward or cumbersome
(which it isn't) but because (no surprise) most of the development world
doesn't really care about portability at all, let alone portability of C++ code
to C compilers.