14

My problem is as follows:

I have a string literal that is macro-ed like so

#define TITLE "Title"

But there are instances when I need to pass in a wide char variant of this string. I want to be able to pass L"Title" to those functions. So naturally, I set out trying to define a new macro W_TITLE in terms of TITLE.

But I have no luck, all my approaches (listed bellow) have failed. Please tell me how such magic can be accomplished.

I tried

#define W_TITLE L##TITLE
#define W_TITLE #L TITLE
#define W_TITLE ##L TITLE

But they all fail...

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • You might like to read here: http://gcc.gnu.org/onlinedocs/cpp/Stringification.html – alk Nov 07 '12 at 17:36

1 Answers1

12

Try this:

#define WIDEN_(exp)   L##exp
#define WIDEN(exp)    WIDEN_(exp)
#define TITLE         "Title"
#define W_TITLE       WIDEN(TITLE)

You need to force an expansion through an intermediate macro to get what you're looking for.

#include <stdio.h>

#define WIDEN_(exp)   L##exp
#define WIDEN(exp)    WIDEN_(exp)
#define TITLE         "Title"
#define W_TITLE       WIDEN(TITLE)

int main(int argc, char *argv[])
{
    printf("%s\n", TITLE);
    wprintf(L"%ls\n", W_TITLE);
    return 0;
}

Result:

Title
Title
WhozCraig
  • 65,258
  • 11
  • 75
  • 141
  • Clever. I would have tried a similar approach, but it wasn't immediately apparent to me. – Cloud Nov 16 '12 at 23:10