4

I'm using g++ compiler, and I want certain lines of my c++ code to be commented out or not commented, depending on my config.

I realise that I could do:

#ifdef DEBUG
cout << "foo" << endl;
#endif

But I would rather it all be on a single line:

#define DEBUG //
DEBUG cout << "foo" << endl;

...with DEBUG being a macro for //. But writing #define DEBUG // yields nothing. Can anyone tell me what to do?

5 Answers 5

5

But I would rather it all be on a single line:
#define DEBUG //

People have given good examples of how to accomplish what you want, but no one has commented on why your approach didn't work.

Your approach will never work. It can't work. There is no mechanism for defining a macro that becomes a start of comment sequence for the simple reason that comments don't exist by the time preprocessor symbols are defined. They have already been stripped out.

Sign up to request clarification or add additional context in comments.

Comments

5

Here's one way of doing it:

#ifdef DEBUG
#define DEBUG_LOG(x) std::cout << x << std::endl;
#else
#define DEBUG_LOG(x)
#endif

DEBUG_LOG("foo")

1 Comment

Also you can write DEBUG_LOG( "variable=" << variable ); in this method, so using all you can use in cout
3

One trick from a Dr. Dobbs article:

#if _DEBUG
// dbgInC defined as "printf" or other custom debug function
#define dbgInC printf
// dbgInCpp defined as "cout" or other custom debug class
#define dbgInCpp cout
#else
// dbgInC defined as null [1]
#define dbgInC
// dbgInCpp defined as "if(0) cerr" or "if(1); else cerr"
#define dbgInCpp if(0) cerr
#endif

This has the advantage of allowing multi-line statements:

dbgInCpp << "Debug in C++: "
<< a // a is an integer
<< b /* b is char array */
<< c // c is a float
<< endl;

1 Comment

+1. You did manage to do it in one line, and it does work for g++. (Lack of portability prevents me using it on my current project.)
0

It is not idiomatic in C. Prefer use the usual form, e.g.:

#ifdef DEBUG
    count << "foo" << endl;
#endif

Or (as assert) :

#ifndef NDEBUG
    count << "foo" << endl;
#endif

For sake of readability. You can also encapsulate this code in a macro:

#ifdef DEBUG
#define PRINT_DEBUG(s) cout << s << endl
#else
#define PRINT_DEBUG(s) (void)0
#endif

Comments

0

You might have

#ifndef NDEBUG
#define DBGOUT(Out) cout << __FILE__ << ":" << __LINE__ << ":" \
  << Out << endl
#else
#define DBGOUT(Out) do {} while(0)
#endif

and use in your code things like

DBGOUT("x is " << x);

I use the NDEBUG symol, because <assert.h> and <cassert> use it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.