如何使用 gcc 模仿 Microsoft 版本的 __FUNCTION__?

问题描述 投票:0回答:2

当我使用

__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 一样简单,如上面的示例所示?

    

c++ windows macos gcc
2个回答
3
投票
Foo::Bar

并且只需按平台进行条件编译。 当然不如宏那么方便,但它可以工作。


与 C++ 中的

__CLASS__ 宏有点相似


2
投票

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:函数局部预定义变量
main foobar foobar barfoo

的定义就像

__func__
形式的定义一样 已提供,其中函数名称是实现定义的字符串。未指定这样的变量是否具有与程序中任何其他对象不同的地址


也就是说,您可能不相信它的价值。如果您想使用非便携式扩展,请查看类似的问题:
What's the Difference Between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

.

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.