Insert double quotes in a macro for pragma in C

Viewed 250

I'm trying to create a macro in C in order to create the correct pragma declaration.

_pragma(section .BLOCK1) //Correct but deprecated
_pragma(section ".BLOCK1") //Correct without warning

Following code is working, but the compiler gives me a warning (deprecated declaration):

#define DO_PRAGMA(x) _Pragma(#x)

#define PRAGMA(number) \
DO_PRAGMA(section .BLOCK##number)

PRAGMA(1)

How I can include the double quotes in the macro? I have already tried inserting "\"", but it is not working because the string is interpreted directly.

2 Answers

You can pass this to a helper macro which expands and stringifies the arguments.

#define _stringify(_x)  #_x

#define DO_PRAGMA(a) _Pragma(_stringify(a))

#define PRAGMA(number) \
    DO_PRAGMA(section _stringify(.BLOCK##number))

The correct way to add double quotes to a macro is indeed to use backslash i.e.:

#define STRING "\"string\""

"string" is now stored in STRING.

To concatenate a number into your macro string you can do something like, but it needs to be stored in non const char array:

#define STRING "section \".BLOCK%d\""
#define CONV(str, n) sprintf(str, STRING, n)
//...
char str [50];
CONV(str, 1);
DO_PRAGMA(str);
//...

If you haven't already, check pragma documentation and this usage example.

Related