by flohofwoe · 6y ago · 0 comments
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).
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.
Nevertheless I received enough requests to make my C libraries 'C++ compliant' that I gave in :)