C99 Macro to create a quoted string literal after evaluation

I am developing an embedded application in C99, and the project contains some integer constants, defined as:

#define LEVEL1     0x0000
#define LEVEL2     (LEVEL1 + 1)

Since then, it has become useful to keep track of these values โ€‹โ€‹for logging purposes, so I would like to use a macro to create a string literal from the evaluated versions above. For instance:

strncpy(str, STRING(LEVEL2), len);

perfect for

strncpy(str, "0x0001", len);

or even

strncpy(str, "0001", len);

Using a two-step macro with the # operator (as suggested by this question ) almost works. He appreciates

strncpy(str, "(LEVEL1 + 1)", len);

I would like to avoid using the runtime function - hence my attempt to solve macros. Suggestions?

+3
source share
2

- , , :

#define STRING1(s) #s
#define STRING(s) STRING1(s)

#define LEVEL(x) x
#define LEVEL1 LEVEL(1)
#define LEVEL2 LEVEL(2)

printf(STRING(LEVEL2));
//2
+2

, C, .

:

, , :

#define LEVEL1 0x0000
#define LEVEL2 0x0001
#define STRING(x)   # x

strncpy(str, STRING(LEVEL2), len);

, .

sprintf snprintf.

#define LEVEL1 0x0000
#define LEVEL2 0x0001

char level[7];
snprintf(level, sizeof level, "%#06x", LEVEL2);
strncpy(str, level, len);

, .

+1

Source: https://habr.com/ru/post/1756847/


All Articles