Search code examples
c++cembeddedesp32arduino-esp32

Two versions of a code based on a #define


I'm working with a microcontroller and writing in C/C++ and I want to separate stuff that's supposed to work only in the transmissor and stuff that will work for the receiver. For this I thought about having a #define DEVICE 0 being 0 for transmissor and 1 for receiver.

How would I use this define to cancel other defines? I have multiple defines that should only work on one of the devices.


Solution

  • You have the following directives:

    #if (DEVICE == 0)
      ...
    #else
      ...
    #endif
    

    To be sure the code will be exclusive.

    Although I recommended to do it dynamically: you can have a boolean global attribute/function parameter and execute code according to its value.

    • The code will be optimized-out on a certain target (even with the lowest optimization setting).
    • One compilation will be enough to check compilation errors instead of 2 with a define change. Bear in mind you will still need a define for the boolean value to be changed and so test every case, but this can be done automatically with any Dynamic code analysis, while not possible with a #define implementation.