(这里指LINUX G++环境)
一,三个重要的宏:
1 __LINE__ 当前的行号
2 __FILE__ 当前的文件名(xxx.cpp)
3 __PRETTY_FUNCTION__/__FUNCTION__ 带签名和不带签名的函数名
二,打印stack trace
通过两个函数:
backtrace();
backtrace_symbols();
需要 -g -rdynamic 参数
- #include <stdio.h>
- #include <exception>
- #include "string.h"
- #include "stdlib.h"
- #include <execinfo.h>
- void print_trace();
- void test();
- void print_trace (void)
- {
- void *array[10];
- size_t size;
- char **strings;
- size_t i;
- size = backtrace (array, 10);
- strings = backtrace_symbols (array, size);
- printf ("Obtained %zd stack frames.\n", size);
- for (i = 0; i < size; i++)
- printf ("%s\n", strings[i]);
- free (strings);
- }
- void test()
- {
- print_trace();
- }
- int main(int argc, char *argv[])
- {
- printf("%d\n", __LINE__);
- printf("%s\n", __FILE__);
- printf("%s\n", __PRETTY_FUNCTION__);
- test();
- return 0;
- }
编译和输出
:!g++ -Wall -g -rdynamic ddd.cpp;./a.out
35
ddd.cpp
int main(int, char**)
Obtained 5 stack frames.
./a.out(_Z11print_tracev+0x16) [0x40090e]
./a.out(_Z4testv+0x9) [0x40098d]
./a.out(main+0x50) [0x4009e0]
/lib64/tls/libc.so.6(__libc_start_main+0xdb) [0x302af1c4bb]
./a.out(__gxx_personality_v0+0x42) [0x40086a]
本文转自 dogegg250 51CTO博客,原文链接:http://blog.51cto.com/jianshusoft/855110,如需转载请自行联系原作者