C Macros to create strings

Richard Stelling picture Richard Stelling · Apr 28, 2009 · Viewed 22.9k times · Source

Alternative Titles (to aid search)

  • Convert a preprocessor token to a string
  • How to 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 some some thing like this:

#ifdef __TESTING
    #define IV_DOMAIN domain.org            //in house testing
#elif __LIVE_TESTING
    #define IV_DOMAIN test.domain.com       //live testing servers
#else
    #define IV_DOMAIN domain.com            //production
#endif

// Sub-Domain
#define IV_SECURE "secure.IV_DOMAIN"             //secure.domain.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?

Answer

Alex B picture Alex B · Apr 28, 2009

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 "domain.org"
#elif __LIVE_TESTING
    #define IV_DOMAIN "test.domain.com"
#else
    #define IV_DOMAIN "domain.com"
#endif

#define IV_SECURE "secure." IV_DOMAIN
#define IV_MOBILE "m." IV_DOMAIN