I was playing around a bit with the C preprocessor, when something which seemed so simple failed:
#define STR_START "
#define STR_END "
int puts(const char *);
int main() {
puts(STR_START hello world STR_END);
}
When I compile it with gcc (note: similar errors with clang), it fails, with these errors:
$ gcc test.c test.c:1:19: warning: missing terminating " character test.c:2:17: warning: missing terminating " character test.c: In function ‘main’: test.c:7: error: missing terminating " character test.c:7: error: ‘hello’ undeclared (first use in this function) test.c:7: error: (Each undeclared identifier is reported only once test.c:7: error: for each function it appears in.) test.c:7: error: expected ‘)’ before ‘world’ test.c:7: error: missing terminating " character
Which sort of confused me, so I ran it through the pre-processor:
$ gcc -E test.c # 1 "test.c" # 1 "" # 1 "" # 1 "test.c" test.c:1:19: warning: missing terminating " character test.c:2:17: warning: missing terminating " character int puts(const char *); int main() { puts(" hello world "); }
Which, despite the warnings, produces completely valid code (in the bolded text)!
If, macros in C are simply a textual replace, why is it that my initial example would fail? Is this a compiler bug? If not, where in the standards does it have information pertaining to this scenario?
Note: I am not looking for how to make my initial snippet compile. I am simply looking for info on why this scenario fails.
#
called stringification. – Jens Gustedt