Quantcast
Channel: 拔剑- 浆糊的传说
Viewing all articles
Browse latest Browse all 255

用栈的方法输出动态调用过程,没啥用,就是好玩

$
0
0
Many debuggers support outputting real-time call-stack information, in this example we use list to output real-time calling stack information in C++. To use it, you just need:
(1) add class and macro to you project;
(2) use MACRO CALL_BACK() in the top of your function, for example:
        void myfunction(int a, int b)
        {
                 CALL_BACK( void myfunction(int a, int b));
      
                // 其他实际代码!
                 
        }
//================================================================
// The following is the source code:
//    by zxg, SISE, SEU
//================================================================
#include < iostream >
#include < string >
#include < list >
using namespace std;

#define CALL_STACK(funct_name)   call_stack update(#funct_name)

class frames
{
protected:
frames() :add_string("   "){}
void enter_frame(const string& frame_name)
{
m_list.push_back(frame_name);
print_stack();
}
void leave_current_frame()
{
string temp = add_string;
list < string> ::reverse_iterator it = m_list.rbegin();
for (list< string > ::iterator it = m_list.begin();
it != m_list.end();
it++)
{
temp += add_string;
}

        it = m_list.rbegin();
cout << temp << "<--Leave frame:" << (*it) << endl;
m_list.pop_back();
//print_stack();
}
protected:
void print_stack()
{
cout << ">>>>>>>>>>>>>>==== call stacks ==============>>>>>" << endl;
string temp = add_string;
for (list < string > ::iterator it = m_list.begin();
it != m_list.end();
it++)
{
temp += add_string;
cout  << temp << "-->"  <<  (*it)  <<  endl;
}
}
protected:
list < string >  m_list;
string       add_string;

public:
friend class call_stack;
};

class call_stack
{
public:

call_stack(const string& funct_name)
{
g_frame.enter_frame(funct_name);
};
~call_stack()
{
g_frame.leave_current_frame();
}
protected:
static frames g_frame;
};

frames call_stack::g_frame;

void say_hi(const char* str="hello,world", const int useless_value=0)
{
CALL_STACK(void say_hi(const char* str = "hello,world", const int useless_value = 0));
cout << "hi" << endl;
}
void do_nothing()
{
CALL_STACK(void do_nothing());
say_hi();
}

void endless_loop(int useless)
{
CALL_STACK(void endless_loop(int useless));
for (int i = 0; i<100;)
{
// do nothing
do_nothing();
}
}
int main(void)
{
CALL_STACK(int main(void));
endless_loop(1);
}

 

Viewing all articles
Browse latest Browse all 255

Trending Articles