user1159517
user1159517

Reputation: 6320

How can I print each function name as the function is called in C++?

I am exploring a large code-base and i am not a gdb fan. I would like add a LOG(INFO) << __PRETTY_FUNCTION__ in the first line of each function in the code-base. But that's very tedious. Does anyone know a hack to make all function calls to print a LOG message with its function name?

Upvotes: 5

Views: 2775

Answers (2)

user2249683
user2249683

Reputation:

I do something similar to:

#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();
}

Upvotes: 3

Pluc
Pluc

Reputation: 911

Seems a duplicate of Automatically adding Enter/Exit Function Logs to a Project

However, You can consider using gprof that has the capability to generate a runtime call tree. You can have dot graphs, which might be easier to read.

Upvotes: 0

Related Questions