-1

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.

  • 2
    `#ifdef DEVICE` and/or `#if DEVICE == 0`? Although I'd suggest setting only correct defines in the build system if that's possible. – Yksisarvinen Mar 30 '22 at 22:50
  • 2
    I'm not sure I understand what you mean by "cancel other defines". If you defined `DEVICE` to be 0 or 1, then `#if DEVICE ... stuff1 ... #else ... stuff2 ... #endif` will only pass `stuff1` if `DEVICE` is 1 and only pass `stuff2` if `DEVICE` is 0. You can put whatever other defines you want inside either block. If you really need to "undefined" (cancel??) an existing define, there's always `#undef`. – lurker Mar 30 '22 at 23:03
  • 2
    Two binaries should be two files. If you have shared functionality, those go in libraries. – Passer By Mar 30 '22 at 23:45
  • 2
    I have seen over-use of conditional compilation clutter too many files and damage readability. Opinion: Only use it for small pieces of hard-to-disentangle code (and question why it's hard to disentangle). For the rest, functions and multiple files. – user4581301 Mar 31 '22 at 00:08

1 Answers1

0

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.
Jocelyn
  • 88
  • 7
  • I got this working, thanks! My problem with using just a simple boolean is tha I have libraries that are used in one device but not the other, so memory starts to become an issue with only 1.5MB approximatelly to work with. Using this method I was able to have enough flash memory for both of the devices! – Vinícius Inacio Breda Apr 03 '22 at 04:39
  • With a minimal optimization you can have it scooped off the binary just like it was a `#ifdef`. With gcc the option is -fdce (Dead Code Elimination) It is enabled by default at -O1 and higher: https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html. Glad you made it work! – Jocelyn Apr 07 '22 at 13:30