Concate define and string in resources

2019-02-23 12:45发布

问题:

I have a resource file where needed create string define with concatenation macros and string, something like this

#define _STRINGIZE(n) #n
#define STRINGIZE(n) _STRINGIZE(n)
#define Word_ Word
100 DIALOGEX 0, 0, 172, 118
STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Hello"STRINGIZE(Word_)=>"Hello"Word" 

but needed simple "HelloWord" without average quotes.

回答1:

For anyone who cares: a .rc file is a resource file from an MFC project that defines UI elements, such as dialog layouts. It uses the same preprocessor as C++, but it does not share C++'s syntax -- and in a window CAPTION field, two string literals won't concatenate by just juxtaposing them. Within a string literal, two double quotes is actually an escape sequence that generates one double quote character. So the literal:

"Hello""World"

ends up looking like

Hello"World

In your dialog Window's caption.

The problem with the example given:

CAPTION "Hello"STRINGIZE(Word_)

Is that the double-quote at the end of "Hello" must be removed, but the preprocessor cannot do this. However, if "Hello" is allowed to be included in a macro, concatenation is possible. First, I defined these macros:

#define CONCAT(a,b) a##b
#define STRINGIZE_(x) #x
#define STRINGIZE(x) STRINGIZE_(x)

then, inside the dialog record:

  ...
EXSTYLE WS_EX_APPWINDOW
CAPTION STRINGIZE(CONCAT(Hello,World))
FONT 10, "Segoe UI Semibold", 600, 0, 0x0
  ...

With this, the dialog's caption ends up looking like HelloWorld -- no stray quotes or anything. I hope you can use this technique.