美文网首页iOS技术文章
Xcode(C/C++)打印调用栈信息

Xcode(C/C++)打印调用栈信息

作者: 熊皮皮 | 来源:发表于2016-05-25 21:00 被阅读1092次

    本文档记录Xcode打印调用栈信息的配置,辅助调试复杂C/C++代码。

    1、输出调用栈信息

    具体功能由由如下函数实现:

    • backtrace:获取当前的调用栈信息,结果存储在buffer中,返回值为栈的深度,参数size限制栈的最大深度,即最大取size步的栈信息。
    • backtrace_symbols:把backtrace获取的栈信息转化为字符串,以字符指针数组的形式返回,参数size限定转换的深度,一般用backtrace调用的返回值。
    • backtrace_symbols_fd:它的功能和backtrace_symbols差不多,只不过它不把转换结果返回给调用方,而是写入fd指定的文件描述符。

    These routines provide a mechanism to examine the current thread's call stack.

    backtrace() writes the function return addresses of the current call stack to the array of pointers referenced by array. At most, size pointers are written. The number of pointers actually written to array is returned.

    backtrace_symbols() attempts to transform a call stack obtained by backtrace() into an array of human-readable strings using dladdr(). The array of strings returned has size elements. It is allocated using malloc() and should be released using free().
    There is no need to free the individual strings in the array.

    backtrace_symbols_fd() performs the same operation as backtrace_symbols(), but the resulting strings are immediately written to the file descriptor fd, and are not returned.

    示例代码:

    #include <execinfo.h>
    #include <stdio.h>
    ...
    void* callstack[128];
    int i, frames = backtrace(callstack, 128);
    char** strs = backtrace_symbols(callstack, frames);
    for (i = 0; i < frames; ++i) {
        printf("%s\n", strs[i]);
    }
    free(strs);
    ...
    

    示例输出:

    backtrace_symbols输出结果示例

    2、GCC -rdynamic无效

    GCC编译标识-rdynamic在Xcode中无论配置在Other C Flags或Other C++ Flags都是无效的,因为配置后输出的栈信息和不配置是相同的。对于Xcode而言,-rdynamic=1是错误的值。

    Other C Flags

    参考与推荐阅读

    相关文章

      网友评论

        本文标题:Xcode(C/C++)打印调用栈信息

        本文链接:https://www.haomeiwen.com/subject/wgvtdttx.html