Use concatenation and stringizing in the same macro with GCC

159 views Asked by At

Those macros are compiled without error with visual studio and codewarrior compilers. With gcc the error is shown in the comment

#define STRINGIFY(x)  #x
#define MYINC(n)      STRINGIFY(extensions/##n##/myinc.h)


#include "extensions/1/myinc.h"          // OK (no surprise)
#include STRINGIFY(extensions/1/myinc.h) // OK
#include MYINC(1)                        // error: pasting "1" and "/" does not give a valid preprocessing token

Some idea?

1

There are 1 answers

1
08822407d On

Actually On my environment (WSL2 gcc9.3), the line

#include STRINGIFY(extensions/1/myinc.h)

event triger compiling error

test1.c:6:10: error: #include expects "FILENAME" or <FILENAME>
    6 | #include STRINGIFY(extensions/1/myinc.h) // OK
      |          ^~~~~~~~~
test1.c:7:17: error: #include expects "FILENAME" or <FILENAME>
    7 | #include MYINC(1)

From GCC document https://gcc.gnu.org/onlinedocs/cpp/Include-Syntax.html I found this:

The argument of ‘#include’, whether delimited with quote marks or angle brackets, behaves like a string constant in that comments are not recognized, and macro names are not expanded. Thus, #include <x/*y> specifies inclusion of a system header file named x/*y.

And MSVC-170 document https://learn.microsoft.com/en-us/cpp/preprocessor/hash-include-directive-c-cpp?view=msvc-170 says:

You can organize constant and macro definitions into include files (also known as header files) and then use #include directives to add them to any source file.

So I guess the problem is some gcc won't expand macro. But if I define:

#define INCFILE "extensions/1/myinc.h"
#include INCFILE

GCC didn't report error. And If I write:

#define INCFILE "extensions/1/myinc.h"
#include STRINGIFY(INCFILE)

GCC also reports:

test1.c:5:10: error: #include expects "FILENAME" or <FILENAME>
    5 | #include STRINGIFY(INCFILE) // OK