C to check: "If multiple defined"

I have several drivers that use a resource in my code, of which only one can be determined. for example, if I have the following definitions: USB_HID, USB_SERIAL, USB_STORAGE. and I want to check that only one of them is defined, is there an easy way to do this? I am currently doing it like this:

#ifdef USB_HID
  #ifdef USB_INUSE
    #error "Can only have one USB device"
  #else
    #define USB_INUSE
  #endif
#endif

#ifdef USB_SERIAL
  #ifdef USB_INUSE
    #error "Can only have one USB device"
  #else
    #define USB_INUSE
  #endif
#endif

... with one of these blocks for each USB_XXX driver. Is there a more elegant way to do this?

+3
source share
3 answers
#if defined(USB_HID) + defined(USB_SERIAL) + defined(USB_STORAGE) != 1
#error Define exactly one of USB_HID, USB_SERIAL, USB_STORAGE
#endif
+10
source

Yes, use an operator define, for example:

#if defined (USB_HID) && defined (USB_INUSE)

0
source

#elif?

#if defined(USB_HID)
   #define USB_INUSE
#elif defined(USB_SERIAL)
   #define USB_INUSE
#endif
0

Source: https://habr.com/ru/post/1777391/


All Articles