当我使用
__FUNCTION__
宏/变量打印调试信息时,使用 Microsoft C++ 编译器和 gcc 时输出的内容似乎有所不同。例如,使用以下简单代码:
class Foo
{
public:
void Bar(int a, int b, int c)
{
printf ("__FUNCTION__ = %s\n", __FUNCTION__);
}
};
int main (void)
{
Foo MyFoo;
MyFoo.Bar();
return 0;
}
使用 Microsoft Visual C++ 编译器,我明白了
__FUNCTION__ = Foo::Bar
而当使用 gcc 编译时(在本例中是在 Mac 上),我得到
__FUNCTION__ = Bar
第二个例子并不理想,因为我经常有几个带有
Init()
和 Uninit()
方法的类,并且在调试输出跟踪中几乎不可能知道其中哪一个被称为类名丢失的。现在,我知道您可以使用 __PRETTY_FUNCTION__
代替 __FUNCTION__
来获得类似 的内容
__PRETTY_FUNCTION__ = void Foo::Bar(int, int, int)
这很好,但是对于我的需要来说有点太冗长了,并且对于具有很多参数的函数来说有点长。
所以我的问题是(最后),有没有办法让输出看起来像使用 gcc 一样简单,如上面的示例所示?
typeid(T).name()
示例:
static const char __func__[] = "function-name ";
但是,用g++输出:
#include <iostream>
namespace meh {
void foobar() { std::cout << __func__ << std::endl; }
};
struct Frob {
void foobar() { std::cout << __func__ << std::endl; }
static void barfoo() { std::cout << __func__ << std::endl; }
};
int main () {
std::cout << __func__ << std::endl;
meh::foobar();
Frob().foobar();
Frob::barfoo();
}
但是,这是有效的 C++ 行为:
§ 8.4.1, 8:函数局部预定义变量
What's the Difference Between __PRETTY_FUNCTION__, __FUNCTION__, __func__?main foobar foobar barfoo
的定义就像
形式的定义一样 已提供,其中函数名称是实现定义的字符串。未指定这样的变量是否具有与程序中任何其他对象不同的地址 也就是说,您可能不相信它的价值。如果您想使用非便携式扩展,请查看类似的问题:__func__