Is there a way to get function name inside a C++ function?(有没有办法在 C++ 函数中获取函数名?)
问题描述
我想实现一个函数跟踪器,它会跟踪一个函数执行的时间.我有以下相同的课程:-
I want to implement a function tracer, which would trace how much time a function is taking to execute. I have following class for the same:-
class FuncTracer
{
    public:
        FuncTracer(LPCTSTR strFuncName_in)
        {
            m_strFuncName[0] = _T(' ');
            if( strFuncName_in ||
                _T(' ') != strFuncName_in[0])
            {   
                _tcscpy(m_strFuncName,strFuncName_in);
                TCHAR strLog[MAX_PATH];
                _stprintf(strLog,_T("Entering Func:- <%s>"),m_strFuncName);
                LOG(strLog)
                m_dwEnterTime = GetTickCount();
            }
        }
        ~FuncTracer()
        {
            TCHAR strLog[MAX_PATH];
            _stprintf(strLog,_T("Leaving Func:- <%s>, Time inside the func <%d> ms"),m_strFuncName, GetTickCount()-m_dwEnterTime);
            LOG(strLog)
        }
    private:
        TCHAR m_strFuncName[MAX_PATH];
        DWORD m_dwEnterTime;
};
void TestClass::TestFunction()
{
    // I want to avoid writing the function name maually..
    // Is there any macro (__LINE__)or some other way to 
    // get the function name inside a function ??
    FuncTracer(_T("TestClass::TestFunction"));
    /*
     * Rest of the function code.
     */
}
我想知道是否有任何方法可以从函数内部获取函数的名称?基本上我希望我班级的用户简单地创建一个相同的对象.他们可能不会传递函数名.
I want to know if there is any way to get the name of the function from inside of a function? Basically I want the users of my class to simply create an object the same. They may not pass the function name.
推荐答案
VC++有
__FUNCTION__ for undecorated names
和
__FUNCDNAME__ for decorated names
你可以编写一个宏,它自己会分配一个对象,并在构造函数中传递名称转换宏.有点喜欢
And you can write a macro that will itself allocate an object and pass the name-yelding macro inside the constructor. Smth like
#define ALLOC_LOGGER FuncTracer ____tracer( __FUNCTION__ );
                        这篇关于有没有办法在 C++ 函数中获取函数名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:有没有办法在 C++ 函数中获取函数名?
				
        
 
            
        基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 常量变量在标题中不起作用 2021-01-01
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 这个宏可以转换成函数吗? 2022-01-01
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				