In the background program to run a problem, the detailed log is an indispensable helper, here provides a way to automatically record the log trigger point file name, line number, function name, the key is to take advantage of C99 new preprocessing identifier __va_args__
We first introduce several compiler built-in macro definitions, these macro definitions can not only help us to complete the cross-platform source code writing, flexible use can also skillfully help us to output very useful debugging information.
There are several standard scheduled macros (also commonly used) in the ANSI C standard:
__line__: Inserts the current source code line number in the source code;
__file__: Inserts the current source filename in the source file;
__date__: Insert the current compilation date in the source file
__time__: Inserts the current compile time in the source file;
__stdc__: The identifier is assigned a value of 1 when the program strictly complies with the ANSI C standard;
__cplusplus: This identifier is defined when you write a C + + program.
Code:
#define LOG (level, format, ...)/do {/ fprintf (stderr, "[%s|%[email protected]%s,%d]" format "/n",/Level , __func__, __file__, __line__, # #__VA_ARGS__); / } while (0) int main () { LOG (log_debug, "a=%d", ten); return 0;}
Operation Result:
[Debug| [Email protected],17] a=10
The restriction is that format cannot be a variable, it must be a constant string, and if a variable string is to be recorded, it cannot be printf (s) like printf, to log ("DEBUG", "%s", s).
There is also another:
============================================================================//name:debug.cpp//author:boyce// version:1.0//copyright:pku//Description:hello World in C + +, ansi-style//========================================== ================================== #include <stdio.h> #define __DEBUG__#IFDEF __debug__#define DEBUG (format, ...) printf ("File:" __file__ ", Line:%05d:" format "\ n", __line__, # #__VA_ARGS__) #else # define DEBUG (format,...) #endifint Main (int argc, char **argv) { char str[]= "Hello World"; DEBUG ("A ha, check me:%s", str); return 0;}
C + + log get function name, line number, file name