3. Display the file/function/line number information where the code is located during C++ debugging

1. Description

When executing C++ code, sometimes you want to know the file name, function name and corresponding line number location information where the current code is located, so that you can quickly locate the code. To obtain this information, you can use some macros provided by C++ to obtain it.

2. Brief explanation

__FILE__ : 用于获取当前语句所在源文件的文件名
——func__ : 用于获取当前语句所在的函数名
__LINE__ : 用于获取当前语句所在的行号位置

When using it, you only need to pass the above three identifiers as parameters. The sample code is as follows:

// 先定义一个函数
void selfTest(int a, int b, const std::string &file, const std::string &func,int line){
    
    
    std::cout << "a + b: " << a + b << "  => " << file << ":" << func << ":" << line << std::endl;
}
// 然后在mian函数中调用
int main() {
    
    
    // 调用时直接将标识符当作参数进行传递即可
    selfTest(3,8,__FILE__,__func__,__LINE__);
}

Compile and execute the file on the linux terminal, the result is as follows:
Insert image description here

3. Simplify writing

In the above method, parameters need to be passed in every time the function is called. The writing method is cumbersome, and the following method can also be used to simplify it

3.1 Separately packaged into functions

Separately encapsulate the function that outputs relevant information into a function, and call this function directly when the location information needs to be output. The sample code is as follows:

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

void logInfo(const string file,const string func,const int line){
    
    
    cout << "File: " << file << " Func: " << func << " Line: " << line << endl; 
}

void selfTest(int a,int b){
    
    
    logInfo(__FILE__,__func__,__LINE__);
    cout << "a + b: " << a + b << endl;
}

int main(){
    
    
    selfTest(3,8);
}

The compilation results are as follows:
Insert image description here

3.2 Using macro definitions and variable parameters

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

void selfTest(int a,int b,const string &file,const string &func,const int &line){
    
    
    cout << "File: " << file << ", Func: " << func << ", Line: " << line << endl;
    cout << "a + b: " << a + b << endl;
}

// 使用的...符号是可变参函数传参的写法,可以使用__VA_ARGS__接收参数
#define selfTest(...) selfTest(__VA_ARGS__,__FILE__,__func__,__LINE__)

int main(){
    
    
    selfTest(3,8);//上面进行宏定义后,此行代码相当于selfTest(3,8,__FILE__,__func__,__LINE__)
}

Guess you like

Origin blog.csdn.net/FY_13781298928/article/details/132685288