Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a C++ macro that acts like a stream

Tags:

c++

c

macros

g++

In the absence of help from Google, I wonder if someone could tell me if it is possible to create a C++ (g++) debug macro that acts like, for example, an "improved" std::cout. Idea is to accept args via << and to append some text so that

DBG << "Hello" << world;

might produce

myfile.cpp 1420 Hello world

I know there are logging libraries(?)/macros(?) out there that do this sortof thing. I'm interested in how it's done, not using some package.

like image 787
Wes Miller Avatar asked Oct 15 '12 20:10

Wes Miller


3 Answers

Your macro could create a temporary variable which invokes endl on destruction. The temporary will stick around until the enclosing expression ends, typically at the ;.

#include <iostream>

struct X {
  ~X() { std::cout << std::endl; }
};

#define DBG (X(), std::cout << __FILE__ << " " << __LINE__ << " ")

int main () {
  std::string world(", world");
  DBG << "Hello" << world;
}
like image 134
Robᵩ Avatar answered Oct 18 '22 23:10

Robᵩ


How about:

#define DBG std::cout << __FILE__ << " " << __LINE__ << " "

http://ideone.com/mN5n3

Close enough! Unfortunatelly, you have to declare the variable world beforehand.

like image 40
Luchian Grigore Avatar answered Oct 19 '22 00:10

Luchian Grigore


The idea behind a debug macro is that it should compile to nothing if you are in release mode. Try this;

#ifdef _DEBUG
    #define MESSAGE(x) (std::cout << __FILE__ << " " << __LINE__ << " " << x);
#else
    #define MESSAGE(x) ;
#endif

int _tmain(int argc, _TCHAR* argv[])
{
    MESSAGE("Hello");
    return 0;
}

When you are in release mode, MESSAGE(x) will have no effect, but in debug mode, you will get a message to the command line.

like image 43
Steztric Avatar answered Oct 18 '22 22:10

Steztric