开发者

How do I imitate the Microsoft version of __FUNCTION__ using gcc?

When I use the __FUNCTION__ macro/variable to print out debugging information, there seems to be a difference in what it outputs when using the Microsoft C++ compiler and gcc. For example, using the following trivial code:

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;
}

Using the Microsoft Visual C++ compiler, I get

__FUNCTION__ = Foo::Bar

whereas when compiling using gcc (in this case on the Mac), I get

__FUNCTION__ = Bar

The second example is not ideal because I quite often have several classes with, say, Init() and Uninit() methods and in a debug output trace its virtually impossible to 开发者_运维百科tell which one of these has been called as the class name will be missing. Now, I know you can use the __PRETTY_FUNCTION__ in place of __FUNCTION__ to get something like

__PRETTY_FUNCTION__ = void Foo::Bar(int, int, int)

Which is fine, but its a bit too verbose for what I need and gets a bit long for functions with a lot of parameters.

So my question is (at last), is there any way to get the output to look like simply Foo::Bar using gcc, as in the example above?


If you are using it for tracing, you can always use typeid(T).name() and just conditionally compile per platform. Certainly not as convenient as the macro, but it could work.

Vaguely similar to __CLASS__ macro in C++


The function-name sanctioned by the standard is defined as follows:

static const char __func__[] = "function-name ";

Example:

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

However, output with g++:

main
foobar
foobar
barfoo

However, that is valid C++ behaviour:

§ 8.4.1, 8: The function-local predefined variable __func__ is defined as if a definition of the form static const char __func__[] = "function-name "; had been provided, where function-name is an implementation-defined string. It is unspecified whether such a variable has an address distinct from that of any other object in the program

I.e., you may not trust in its value. If you want to use non-portable extensions, have a look at a similar question: What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__? .

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜