Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a "C single-line comment" macro

I am trying to create a "single line comment" macro in C, this is used conditionally to comment out lines of codes, according to some global macro definitions. It is the same idea expressed in this article.

Trying many permutations of this code, I keep getting error messages from the compiler.

For example, directly following the code sample from that page:

#define COMMENT SLASH(/)
#define SLASH(s) /##s
#define DEBUG_ONLY COMMENT
DEBUG_ONLY a = b;   // <-- line #83

GCC gives the following error:

prog.c:83:1: error: pasting "/" and "/" does not give a valid preprocessing token
prog.c:83: error: expected expression before ‘/’ token

As mentioned, I played with that theme and tried many variations but all fail giving similar diagnostics.

What am I doing wrong, and why doesn't the code from the article compiles well?

like image 816
ysap Avatar asked Mar 21 '13 10:03

ysap


3 Answers

I used #define cout(x) //cout<<x; for my applications. You may want to modify it like

#ifdef DEBUG
#define cout(x) cout<<x;
#else
#define cout(x)

And use it as

cout(arg0<<arg1<<arg2);

Here, you won't be commenting the line and thus won't need separate line for avoiding print. Further you can use cout wherever printing has to be done unconditionally.

cout("Print this when debugging");
cout<<"Always print this";
like image 170
Himanshu Tanwar Avatar answered Oct 25 '22 09:10

Himanshu Tanwar


It doesn't work because the language specification doesn't allow it. In effect, comment removal happens before macro replacement. Once comments have been removed, // is not a valid token (like the error message says). It can't be generated by macro replacement, and it no longer means "comment".

This is "Translation phases" in the standard. The section numbering differs, but all of C89, C99 and C11 define in phase 3:

Each comment is replaced by one space character.

and then in phase 4:

macro invocations are expanded

like image 45
Steve Jessop Avatar answered Oct 25 '22 08:10

Steve Jessop


A debug macro:

#define DEBUG(x) x

Which can be turned off in production as:

#define DEBUG(x)

Or IIRC #undef (sorry, my C is rusty).

like image 25
djechlin Avatar answered Oct 25 '22 08:10

djechlin