cmacrosc-preprocessorstringification

Macros to create strings in C


Alternative titles (to aid search)

  • Convert a preprocessor token to a string
  • How can I make a char string from a C macro's value?

Original Question

I would like to use C #define to build literal strings at compile time.

The string are domains that change for debug, release, etc.

I would like to do something like this:

#ifdef __TESTING
    #define IV_DOMAIN example.org            // In house testing
#elif __LIVE_TESTING
    #define IV_DOMAIN test.example.com       // Live testing servers
#else
    #define IV_DOMAIN example.com            // Production
#endif

// Subdomain
#define IV_SECURE "secure.IV_DOMAIN"         // secure.example.org, etc.
#define IV_MOBILE "m.IV_DOMAIN"

But the preprocessor doesn't evaluate anything within ""

  1. Is there a way around this?
  2. Is this even a good idea?

Solution

  • In C, string literals are concatenated automatically. For example,

    const char * s1 = "foo" "bar";
    const char * s2 = "foobar";
    

    s1 and s2 are the same string.

    So, for your problem, the answer (without token pasting) is

    #ifdef __TESTING
        #define IV_DOMAIN "example.org"
    #elif __LIVE_TESTING
        #define IV_DOMAIN "test.example.com"
    #else
        #define IV_DOMAIN "example.com"
    #endif
    
    #define IV_SECURE "secure." IV_DOMAIN
    #define IV_MOBILE "m." IV_DOMAIN