Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to compare strings in C preprocessor? (GCC) [duplicate]

Is there a better way to do this (in GCC C)?

I'm trying to define some symbols representing the hardware platform, to be used for conditional compilation.

But I also want printable strings describing the hardware (for diagnostics).

Ideally I'd like be able to do:

#define HARDWARE "REV4C"

#if (HARDWARE == "REV4C")
    #define LED_RED      // define pin addresses, blah blah...
#endif

printf("HARDWARE %s\n", HARDWARE);

But I don't think that's allowed in C. This works, but it's ugly:

#define REV4C   (403)    // symbols for conditional compilation
#define REV421  (421) 

//#define HARDWARE REV4C // choose hardware platform (just one)
#define HARDWARE REV421

#if (HARDWARE == REV421) // define strings for printing
    #define HARDWARE_ID "REV421"
#elif (HARDWARE == REV4C)
    #define HARDWARE_ID "REV4C"
#else
    #define HARDWARE_ID "unknown"
#endif

#if (HARDWARE == REV421)
    #define LED_RED      // define pin addresses, blah blah...
#endif

/* ... */

printf("HARDWARE_ID %s\n", HARDWARE_ID);

This is ugly because it requires two separate symbols, HARDWARE (an integer, for comparison) and HARDWARE_ID (a string, for printing). And logic to generate the value of HARDWARE_ID.

Is there a better way?


Edit: I don't think this is a duplicate of how to compare string in C conditional preprocessor-directives.

That question (and answer) doesn't address how to get a printable string without ending up with two similar symbols.

(I did look at that answer before posting this question.)

like image 952
nerdfever.com Avatar asked Oct 20 '25 04:10

nerdfever.com


2 Answers

The usual way of doing it is just to define the required configuration symbol, and then conditionally to define all of the others:

// Select config here
#define REV4C
//#define REV421

#ifdef REV4C
    #define HARDWARE_ID "REV4C"
    #define LED_RED
#elif defined(REV421)
    #define HARDWARE_ID "REV421"
    // .....
#else
//.......
#endif
like image 179
Eugene Sh. Avatar answered Oct 22 '25 19:10

Eugene Sh.


To do the actual case analysis look at the comment that marks this as duplicate. To actually also have the value as a string you can use stringification, something like

#define STRINGIFY(...) #__VA_ARGS__
#define HARDWARE_STR STRINGIFY(HARDWARE)
like image 42
Jens Gustedt Avatar answered Oct 22 '25 19:10

Jens Gustedt