cc-preprocessor

Make a preprocessor string macro NOT expand things within the string


prog.c has

    #include <stdio.h>
    #define STR(x) _STR(x)
    #define _STR(x) #x

    int main()
    {
      const char *s = STR(MYPATH);
      puts(s);
    }

and is compiled with cc -DMYPATH=/usr/linux/path prog.c

This results in /usr/1/path being printed because linux expands to 1 in the compiler (on my Linux machine). How do I prevent this? Obviously I want /usr/linux/path to be printed.


Solution

  • Instead of attempting to make a string literal via macro replacement, pass the path to the compiler with quotes.

    Change const char *s = STR(MYPATH); to const char *s = MYPATH;

    And change the compilation command to cc -DMYPATH='"/usr/linux/path"' prog.c (options for escaping the quotes in the command may vary by the command shell used).