是否有可能在GCC中获得正在编译的函数的名称?

Is it possible to get the name of the function being compiled in GCC?

本文关键字:函数 编译 GCC 有可能 是否      更新时间:2023-10-16

对不起,我甚至不知道该怎么问。

我想生成一些正在运行的方法或函数的跟踪日志,但我不想在每个方法中都写命令名(我真的很懒!)。

的例子:

我的当前代码:

void doSomething() {
    TRACE("doSomething");
    // now do something!
    system("pause");
}

我想做什么:

void doSomething() {
    TRACE;
    // do something!
    system("pause");
}

期望输出(两个程序):

doSomething
Press any key to continue...

如果你需要我说得更清楚,请告诉我。我尽量说得清楚些

我会这样开始:

#define TRACE(message) TRACE_IMPL(__FILE__, __LINE__, __PRETTY_FUNCTION__, message)
void TRACE_IMPL(const char *file, int line, const char *function, const char *message) {
    ...
}
int main() {
    TRACE("help");
}

我的下一步是将message更改为格式字符串,并在Trace上启用printf()样式va_args。它看起来像:

#include <cstdio>
#include <stdarg.h>
#define TRACE(format, ...) TRACE_IMPL("File: %s Line: %d Function: %s Message: " format "n", __FILE__, __LINE__, __PRETTY_FUNCTION__, ##__VA_ARGS__)
void TRACE_IMPL(const char *format, ...) {
    va_list args;
    va_start(args, format);
    vprintf(format, args);
    va_end(args);
}
int main() {
    TRACE("help");
    TRACE("Canary %d", 2);
}

输出:

[8:18pm][wlynch@watermelon /tmp] ./foo
File: foo.c Line: 14 Function: int main() Message: help
File: foo.c Line: 15 Function: int main() Message: Canary 2

如果你愿意,你也可以使用c++流:

#include <iostream>
#define TRACE LogImpl(__FILE__, __LINE__, __PRETTY_FUNCTION__)
class LogImpl {
    public:
        LogImpl(const char *file, int line, char *function) {
            std::cout << "File: " << file << " Line: " << line << " Function: " << function << " Message: ";
        }
        ~LogImpl() {
            std::cout << "n";
        }
        LogImpl(LogImpl const &) = delete;
        LogImpl & operator=(LogImpl const &) = delete;
        template <typename T>
        LogImpl & operator<<(T const & obj) {
            std::cout << obj;
            return *this;
        }
};
int main() {
    TRACE << "help";
    TRACE << "Canary " << 2;
}