Hacker News new | ask | show | jobs
by wolletd 616 days ago
I wonder how hard it would be to just convert old C code to C++?

I mean, most of C just compiles as C++ and does the right thing. There may be some caveats with UB (but less if you don't switch compiler vendor) and minor syntactic differences, but I guess most of them could be statically checked.

Or is there any other (performance/size) reason to not do this?

6 comments

> I mean, most of C just compiles as C++ and does the right thing.

In my experience, unless you’re strictly talking about header files (which I’m assuming you’re not), C code compiling via C++ compilers is usually hit or miss and highly dependent on the author of the C code having put in some effort into making sure the code actually compiles properly via a C++ compiler.

In the overwhelming majority of cases, what lots of folks do is just slap that `extern "C"` in between `#ifdef __cplusplus` and call it a day—that may work for most forward declarations in header files, but that’s absolutely not enough for most C source files.

By the way, a great example of C code that does this exceptionally well is Daan Leijen’s awesome mimalloc [0]—you can compile it via a C or C++ compiler and it simply just works. It’s been a while since I read the code, but when I did, it was immediately obvious to me that the code was written with that type of compatibility in mind.

[0]: https://github.com/microsoft/mimalloc

There are pretty fundamental differences in key areas, like zero initialization of a struct or array (`{0}` vs `{}`). Use the C way in C++ and you only 0 the first element or member. Use the C++ way in C and you don't 0 anything.

IMO there's no point even attempting a blind recompile of C as C++. A transpiler tool would be needed.

`int array[100] = {0};` results in an array with 100 zeroes in both C and C++. In C if there are too few values the remaining ones are initialized following the same rules as for static variables, and in C++ they're initialized using value initialization. For all types supported by C these have the same result.
We could fire WG14 and add Walter Brights fix for passing arrays, buffer and slice types. Add phat pointers and types as fist class objects.

If you did that and implemented marking passing size info over function calls then you could probably mechanically convert crappy foo(void *buf, int sz) code to foo(slice_t buf) which would be a lot safer to maintain.

> I mean, most of C just compiles as C++

You're asking about old C code - that code won't compile as C++. And newer C code would likely also be cleaner and not benefit much from being compiled as C++.

(And, C++ is a net negative over C anyway due to much poorer reviewability.)

> most of C just compiles as C++

um, not unless explicitly written to so.

The ABI for C++ is a disaster. That alone would doom such a conversion.