Create a C ++ macro that acts like a stream

In the absence of help from Google, I wonder if anyone can tell me if it is possible to create a C ++ debug macro (g ++) that acts, for example, as an "improved" std :: cout. The idea is to take arguments via <and add some text to

DBG << "Hello" << world; 

can produce

 myfile.cpp 1420 Hello world 

I know there are log magazines (?) / Macros (?) That do this thing. I am wondering how to do this and not use any kind of package.

+4
source share
3 answers

Your macro can create a temporary variable that calls endl when destroyed. Temporary will stick until the closing expression ends, usually on ; .

 #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; } 
+12
source

What about:

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

http://ideone.com/mN5n3

Close enough! Unfortunately, you need to declare the world variable in advance.

+6
source

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

 #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 not have any effect, but in debug mode you will receive a message on the command line.

+1
source

Source: https://habr.com/ru/post/1439916/


All Articles