简体   繁体   中英

Macros and multi-line comments

I need to have multi-line comments within a group of macros so that one of the macros initiates a comment block and another concludes it, like this:

#define C_BEGIN /*
#define C_END */
... other macros

But sure enough, this approach doesn't work.

You can't do it for the following reasoning. Let's assume it is possible.

So you created a macro that replaces itself with /* , and another for */ . What happens then? First, the comments are removed from the code. After that, the preprocessor replaces your macros with the comments. After that, the compiler will choke: it doesn't know what to do with /* and */ because it simply never faces such things: the comments are always delete before the compilation, so it doesn't even know what a "comment" is. It will probably think it's a division followed by multiplication.

So our assumption is wrong and you can't do it.

Comment processing happens before macro expansion:

2.2 Phases of translation [lex.phases]

1 - The precedence among the syntax rules of translation is specified by the following phases. [...]
3. [...] Each comment is replaced by one space character. [...]
4. Preprocessing directives are executed, macro invocations are expanded [...]

Perhaps you could try preprocessing your source file twice? (Note: don't do this.)

But sure enough, this approach doesn't work.

It can't work. The comment in your #define C_BEGIN is not a part of and cannot be a part of your macro definition. As far as the language is concerned, your #define C_END is not a macro definition. It just a part of that multiline comment. In other words, it is whitespace. Comments are processed (turned into whitespace) before the preprocessor / compiler gets to the stage of interpreting your macro definitions.

If you are using an IDE, you can simply press ctrl / for Windows or command / on Mac. You should select the lines you want to comment first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM