stbtrax
stbtrax

Reputation: 205

C macro to test: "If more than one defined"

I have several drivers using a resource in my code, of which only one can be defined. eg if I have the following defines: USB_HID, USB_SERIAL, USB_STORAGE. and I want to test that only one is defined, is there a simple way to do this? Currently I am doing it this way:

#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 more elegant way of doing this?

Upvotes: 4

Views: 958

Answers (3)

Patrick Schlüter
Patrick Schlüter

Reputation: 11841

Why not #elif ?

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

Upvotes: 0

Jack Kelly
Jack Kelly

Reputation: 18667

#if defined(USB_HID) + defined(USB_SERIAL) + defined(USB_STORAGE) != 1
#error Define exactly one of USB_HID, USB_SERIAL, USB_STORAGE
#endif

Upvotes: 15

SiegeX
SiegeX

Reputation: 140327

Yes, use the define operator such as:

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

Upvotes: 0

Related Questions