cc-preprocessor

How to include a double quote in a C macro defintion?


I have the following test program:

#define q "

int main() {
    printf(q hello world q);
}

Compiling this with gcc (I've tried both versions 12.3 and 11.4 on Ubuntu) produces this error: error: missing terminating " character on line 1. Compiling with clang (Apple clang version 11.0.0) produces the error error: expected expression on line 4.

Now, I had always assumed that, when a C program was compiled, the preprocessor ran first, handled all of the preprocessor directives, and then the output of the preprocessor was read by the complier proper.

Running this test program through the gcc preprocessor (gcc -E) produces a warning, but no errors, and yields this sensible output:

int main() {
    printf(" hello world ");
}

This program will now compile without errors and runs just fine. So, while I can't compile the original program directly, if I run the preprocessor manually and compile the result, then it works. This violates my (apparently mistaken) understanding of how the preprocessor and the compiler operate together.

So, I have two questions:

  1. Is it possible to include a double quote character (but not two of them) in the definition of a C macro?

  2. What is happening with the preprocessor and compiler in this example that allows it to compile and run if I run the preprocessor manually, but not when the preprocessor is run automatically as part of the compilation process?


Solution

  • The C preprocessor deals with tokens (and token sequences), not individual characters, and tokenization happens before preprocessing. That means you can't manipulate things in the preprocessor that are not tokens -- and a bare " is not a token, it is part of a string literal token.

    You might be able to do something more like what you want by using a more general macro processor like m4