1. Overview
After the const keyword is in C + +, the function of the macro definition constants is no longer recommended. This makes the macros seem useless. In fact, the macro can do a lot of things, the author is difficult to enumerate all. Here, just a few typical usage, I hope you can benefit from it.
2. Realize multi-environment compatibility
The common scenario is that we implement a function that wants it to only be satisfied in some kind of compilation condition that is compiled and used. For example, I want to insert a debug statement in the source code so that when I run in debug mode, I can observe the program's performance through debugging information. However, when the product is sold to the user, I hope that the debugging information does not output to reduce code size and improve performance. The solution to this problem is to use macros. According to conditional compilation directives, different implementations are provided for different compiling conditions. For example, we want to write the current line number and file name to the log at a specific location to determine if the corresponding code is being executed, and you can use the following macro:
#ifdef _DEBUG
#define TRACE_FILE_LINE_INFO() do{\
CString str;\
str.Format(_T("file=%s,line=%u\r\n",__FILE__,__LINE__);\
CFile file("logfile.txt");\
file.Write(str,str.GetLength());\
}while(0)
#else
#define TRACE_FILE_LINE_INFO()
#endif
The above code, through the #ifdef #else #endif三个条件编译 instructions, determines the implementation of the specific Trace_file_line_info macro function based on the _DEBUG definition (the macro used to differentiate between debug and release versions). Users can use the following methods
TRACE_FILE_LINE_INFO();//这里显示行号和文本信息
Of course, this can be achieved in other ways, but using macros has the following special benefits: Only the required code is compiled, the size of the symbol table is reduced, and the code dimension macro is expanded at compile time, so the __FILE__,__LINE__ macro that represents the location of the code can work, If implemented with a function, these two macros will not work.