unwind callstack on Linux


// callstack.cpp
#define UNW_LOCAL_ONLY
#include < stdio.h > 
#include < libunwind.h > 

void show_backtrace(void) {
 unw_cursor_t cursor; unw_context_t uc;
 unw_word_t ip, sp;

 unw_getcontext(&uc);
 unw_init_local(&cursor, &uc);
        char buf[512];
 while( unw_step(&cursor) > 0) {
  // unw_get_reg(&cursor, UNW_REG_IP, &ip);//uncomment these if you want to print ip and sp pointers.
  // unw_get_reg(&cursor, UNW_REG_SP, &sp);
//  printf("ip = %lx, sp = %lx\n", (long) ip, (long) sp);
              unw_get_proc_name(&cursor,buf,sizeof(buf),NULL);
              printf("%s\n",buf);

 }
}


$ gcc callstack.cpp -m32 -lunwind

use this show_backtrace function in your code where ever exceptions come. you can print the callstack on console.