如何在C中调用函数时打印每个函数名称?

我正在探索一个庞大的代码库,我不是一个gdb粉丝.我想添加一个

LOG(INFO)<< __PRETTY_FUNCTION__位于代码库中每个函数的第一行.但那非常乏味.有没有人知道要进行所有函数调用以打印带有其函数名称的LOG消息? 最佳答案 我做了类似的事情:

#include <iostream>

class LogScope
{
    public:
    LogScope(const char* scope, const char* file, int line = 0)
    :   m_scope(scope), m_file(file), m_line(line)
    {
        std::clog << "[Begin] " << m_scope << ", " << m_file << ", " << m_line << std::endl;
    }

    ~LogScope() {
        std::clog << "[End]   "  << m_scope << ", " << m_file << ", " << m_line << std::endl;
    }

    private:
    const char* m_scope;
    const char* m_file;
    int m_line;
};

#define NAME_AT_LINE_2(Name, Line) Name##_##Line
#define NAME_AT_LINE_1(Name, Line) NAME_AT_LINE_2(Name, Line)
#define NAME_AT_LINE(Name) NAME_AT_LINE_1(Name, __LINE__)

#define LOG_SCOPE \
    ::LogScope NAME_AT_LINE(log_scope)(__FUNCTION__, __FILE__, __LINE__)

void f() {
    LOG_SCOPE;
}

int main() {
    LOG_SCOPE;
    f();
}
点赞