jeudi 15 juin 2023

Turning features on/off at compile time: #if vs. wrapper vs. empty implementation

I have a C codebase for some embedded project that can be configured to run on a number of different PCBs with different hardware peripheral devices.

Configuration files dictate which of these devices are enabled or disabled, and I could use something like

#if FEATURE
do_something()
#endif

in order to enable it.

I can also use these variables in the build scripts to turn compilation of files on/off conditionally.

Now in my case calls that interact with these devices are all over the code. But, I don't want the implementation of these calls to be compiled into the binary, as it increases the size and allocates things like static variables which eat up my precious RAM (including some large buffers for storing messages that go up a network stack, for instance).

So I could use these #if statements all over the code to prevent compilation errors when I turn off compilation of the relevant .c files (but include the interface .h files). But even then, it becomes quite an "ifdef hell" which in my opinion makes the code badly readable.

So I've been trying to come up with alternatives. The options I have thought of so far:

  1. use wrapper functions that contain the #ifdef inside, so the main code does not suffer from this unreadability:
void do_something() {
#if FEATURE
    do_something_inner();
#endif
}
  1. add a different "dummy" .c file with an empty implementation for each interface I want to turn off and compile that .c file instead of the real implementation whenever my feature is turned off (or vice versa):
/// something_dummy.c
void do_something(){}

/// something_real.c
void do_something(){
    implementation goes here
}

What do you think is the best option and why? Or is there an option I haven't thought of?

(If it matters, I'm using Zephyr RTOS and generate the configuration using KConfig, which can be passed into both CMake and a C file containing the relevant #defines).

Aucun commentaire:

Enregistrer un commentaire