This question is related to Concatenate string literal with char literal, but is slightly more complex.
I would like to create a string literal, where the first character of the string is the length of the string, and the second character is a constant. This is how it is being done currently:
const char myString[] =
{
0x08,
SOME_8_BIT_CONSTANT,
'H',
'e',
'l',
'l',
'o',
0x00
};
Ideally, I would like to replace it with something like:
const char myString[] = BUILD_STRING(0xAA, "Hello");
I tried implementing it like this:
#define STR2(S) #S
#define STR(S) STR2(S)
#define BUILD_STRING(C, S) {(sizeof(S)+2), C, S}
const char myString[] = BUILD_STRING(0xAA, "Hello");
but it expands to:
const char myString[] = {(sizeof("Hello")+2), 0xAA, "Hello"};
and the compiler doesn't seem to like mixing numbers and strings.
Is there any way to do this?
sizeofyou are no longer in pre-processing stage: might as well write a proper function.BUILD_STRING(C, "foo");to{sizeof "foo" + 2, C, "foo"[0], "foo"[1], …}then that would fulfil OP’s requirements. I don’t think there’s a way but maybe I’m missing something.sizeofwill be evaluated at compile time (except in the case of VLAs, which isn't relevant here), so it still satisfies OPs requirements.