Hacker News new | ask | show | jobs
by flohofwoe 2388 days ago
As a warning: While C99 is a really nice language - especially over C89 - please note that the Visual Studio C compiler still does not support the full C99 specification, and it is not possible at all to compile C99 as C++ code (which sometimes is useful).

I usually recommend to write library-level code in the "subset of C99 which compiles both in C and C++ mode on GCC, clang and MSVC". This is basically a version of C that's somewhere C89 and C99 (basically a "C95").

Another quite valid option is to define a pure C-API first, but implement the "inner library code" in a simple C++ (just be careful with "modern C++", since this usually results in increased compilation time and binary size).

2 comments

The one feature from C99 that I rely on (from the top of my head) is designated initializers which is still not in C++...

    enum {
        FPGAPARAM_FOO,
        FPGAPARAM_BAR,
        FPGAPARAM_BAZ,
        NUM_FPGAPARAM_KINDS
    };

    struct FpgaparamInfo {
        const char *name;
        int address;
        int args;
    };

    static struct FpgaparamInfo fpgaParamInfo[NUM_FPGAPARAM_KINDS] = {
        [FPGAPARAM_FOO] = { "FOO", 0x1337, -1 },
        [FPGAPARAM_BAR] = { "BAR", 0x666, -1 },
        [FPGAPARAM_BAZ] = { "BAZ", 0x42, -1 },
    };
The FpgaParamInfo is basically a mapping from a FPGAPARAM_??? value to additional information. We can make as many of these mappings as we want, and can define them where we want, which means it's all nicely modular. That's not really possible when modelling in a OOP fashion.

I really like this style of programming since it's data first and it minimizes the amount of actual code. Designated initializers are important because the order in which the items in "fpgaParamInfo" are given doesn't matter. Without designated initializers, programming in this style would probably lead to many hard to find bugs when the enum is changed and not all associated data items are updated.

Thanks for the comment, I might steal your "subset of C99 which compiles both in C and C++ mode on GCC, clang and MSVC" quote and put it in the article if that's ok ;)
Is there a benefit to building C code with a C++ compiler?
C++ has some stricter type checking by default, but most of this can be achieved by raising the warning level when compiled as C.

Nevertheless I received enough requests to make my C libraries 'C++ compliant' that I gave in :)

Only if your project is already mostly C++ and you would like to use your C++ compiler for everything, to keep the build process simpler.