Hacker News new | ask | show | jobs
by meson2k 3924 days ago
The emitted code is highly name mangled - one of the reasons why you encapsulate the C code in "extern C" https://en.wikipedia.org/wiki/Name_mangling
1 comments

That seems like a problem that has quite a few possible solutions: deterministic name mangling, hinting in the source as to how the name should be mangled, an external mapping of mangling exceptions and/or rules to be used by the transpiler. None of those are mutually exclusive, all could be used together.
It's more than that - there's extra information that's compiled alongside your runtime data structures whenever you write C++. For example, every class with virtual member functions has a vtable, and every object of such a class has a pointer to the vtable. Every time you access a virtual member function, it's indirecting through the vtable to find the particular address to call, and then calling it with the object itself as the first argument.

If you got rid of name mangling (and a few other C++ features that are besides the point), you could certainly call C++ from C. The thing is - your C calls would look exactly like what the article is suggesting. That's why it's important to learn this technique: it is what your C++ compiler is doing under the hood. Indeed, the very first C++ compilers were just preprocessors that transformed C++ syntax into the type of vtable + base class + first parameter indirection that you see here.

Yes, so while this technique would be harder to adopt for a library, or at least harder on the users, for an application where you don't really need to worry about people using C calling into your code, it would be fairly useful. A short HOWTO on how to call from C using the necessarily included and emulated C++ vtable bits would make calling in from C possible and easier where required, but you could still reap the benefits of non-C features while sticking with a C toolchain at the lowest level.
Usually an 'extern "C" { .... }' declaration is easier if you control the C++ library code.
I see what's being talked about now. I misinterpreted meson2k's original reply, so haven't really been on the same page as you or him.

If current C++ to C transpilers don't handle naming well, that's a problem that should be worked on.