1. 9
  1. 8

    I’ve tried to use C++ in the Linux and FreeBSD kernels.

    For FreeBSD, it was relatively simple. There are a few things that are macros and should be functions (e.g. pause, which conflicted with a method name) but that’s easy to work around with some shims and I was able to run a kernel module with a few thousand lines of C++ without problems (I also have a port of libc++ to run in the kernel and an implementation of the emuTLS ABI for FreeBSD 11, in C++, so that thread_local can work in the kernel, though it’s a bad idea to actually use it). After a compiler update, I found that the compiler was emitting a relocation that the kernel’s loader didn’t understand and, since this was just an experiment, I didn’t bother chasing it down.

    The bigger problem in general was that it was fine to use C++ for a module, but C++’s ODR depends on deduplication for static linking and copy relocations for sharing. I had some thoughts about writing some tooling that could be run at module-install time to remove symbols that were defined in modules that you depended on (including the kernel) but I never got around to it.

    For Linux, the kernel headers are completely full of things that are valid C but not even GNU extensions in C++. Using class as an identifier was the least of it - that’s trivial to work around with:

    #define class class_identifier
    extern "C" {
    #include <some/header.h>
    }
    #undef class
    

    The biggest thing, as I recall, was string literals with another token immediately following them, which are user-defined literals in C++. These are all fixable, and if Linus didn’t have a religious objection to C++ then I’d be tempted to try, but I don’t want to carry a downstream fork of the kernel headers.

    1. 2

      I hate strings. They seem like such a simple concept, but in the end they require too much work. Something as simple as character width becomes nuanced very quickly.

      Why use wide strings at all? The kernel presumably uses char*, so just use plain std::string. I have never once used C++ wide strings; UTF-8 works much better.

      The issue with CPU registers Isn’t a C/C++ difference, just a failure to use the right set of compiler flags to match the kernel’s ABI.