Demangle C++ function name at runtime

C++的函數名稱都會mangle

靜態Demanlge只要使用c++filt指令就能處理
動態的Demangle需要使用libstdc++的功能或是libliberty提供的函數功能

#include <iostream>
#include <stdlib.h>
#include <typeinfo>
#include <cxxabi.h> // libstdc++
#include <libiberty/demangle.h> // libliberty

// Prerequirement for Ubuntu
// sudo apt-get install libiberty-dev

// Please compile with -liberty
// example: gcc test.cpp -liberty

using namespace std;

int main(int argc, char** argv) {
    char* demangled_name = NULL;
    int status;
    int options = DMGL_PARAMS | DMGL_ANSI | DMGL_TYPES;
    if (argc<=1) {
        cerr << "Please assign a mangling C++ function name" << endl;
        return -1;
    }
    cout << "Demangle the mangling string [" << argv[1] << "]" << endl;

    // libstdc++
    // https://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html
    demangled_name = abi::__cxa_demangle(argv[1],0,0,&status);
    if (demangled_name) {
        cout << "abi::__cxa_demangle = " << demangled_name << endl;
        free(demangled_name);
    } else {
        cerr << "Invalid C++ mangling string for abi::__cxa_demangle" << endl;
    }

    // libliberty
    // https://gcc.gnu.org/onlinedocs/libiberty/
    demangled_name = cplus_demangle(argv[1], options);
    if (demangled_name) {
        cout << "cplus_demangle = " << demangled_name << endl;
        free(demangled_name);
    } else {
        cerr << "Invalid C++ mangling string for cplus_demangle" << endl;
    }
    return 0;
}

留言