Jellicle
Jellicle

Reputation: 30206

Debugging comments and C/C++ macros

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?

Upvotes: 4

Views: 1733

Answers (5)

David Hammen
David Hammen

Reputation: 33106

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.

Upvotes: 5

pb2q
pb2q

Reputation: 59607

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;

Upvotes: 3

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.

Upvotes: 0

Cornstalks
Cornstalks

Reputation: 38217

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")

Upvotes: 5

md5
md5

Reputation: 23699

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

Upvotes: 0

Related Questions