C/C++ compiler predetermined macro usage

        In the C/C++ compiler, there are compiler-level predefined macros, __FILE__, __LINE__, __FUNCTION__, __DATE__, __TIME__, etc.

       Let's introduce the meaning of these macros one by one:

       __FILE__ The file name of the current file, GCC under linux only has the file name, while under Windows GCC will contain the complete path, which can be set to only the file name through the compile option;

       __LINE__ The current line number of the code;

       __FUNCTION__ The name of the function where the current line is located;

       __DATE__ the current date;

      __TIME__ Current time.

The following describes the usage of these macros.

#include <iostream>
#include <string>
using namespace std;

int main()
{
    cout << "Date:" << __DATE__
         << " Time:" << __TIME__
	 << endl;
    cout <<"File:" << __FILE__ 
         <<", Line:" << __LINE__ 
         <<", Function:" << __FUNCTION__ 
         << endl;
    return 0;
}
After compiling under linux, the execution result is as follows:

Date:Apr 27 2017 Time:13:59:55
File:test.cpp, Line:11, Function:main
When we debug the program, these macros are very convenient for our debugging. For example, we can use these macros to print information at the exception exit of the function to locate the specific file, function, and code line of the program exception. E.g:

#define DEBUG

#ifdef DEBUG
#define DEBUG_ERR_LOG()  cout << "Err File:" << __FILE__ << ", Line:" << __LINE__ << ", Function:" << __FUNCTION__ << endl;
#else
#define DEBUG_ERR_LOG()
#endif

In this way, we can use DEBUG_RRR_LOG() to print such information directly where we want to output an exception.

Of course, you can also use these macros to print debugging information in other combinations.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324364103&siteId=291194637