Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Macros to create strings

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?
like image 309
Richard Stelling Avatar asked Apr 28 '09 14:04

Richard Stelling


People also ask

Can a macro be a string?

Example# Macros are simple string replacements.

What is a Stringize operator?

Stringizing operator (#) The number-sign or "stringizing" operator (#) converts macro parameters to string literals without expanding the parameter definition. It's used only with macros that take arguments.

What does ## mean in macro?

The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token, and therefore, can't be the first or last token in the macro definition.

How do you use #define C++?

Remarks. The #define directive causes the compiler to substitute token-string for each occurrence of identifier in the source file. The identifier is replaced only when it forms a token. That is, identifier is not replaced if it appears in a comment, in a string, or as part of a longer identifier.


1 Answers

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 
like image 124
Alex B Avatar answered Oct 08 '22 03:10

Alex B