简体   繁体   中英

std::chrono gdb pretty printer

I am mildly surprised that gdb doesn't come with pretty printers out of the box for the std::chrono duration types since they are part of the standard library. With gdb 10.2 (through most recent Clion IDE although that should not be Clion specific - it's plain gdb under the hood) I see the unhelpful:

system_clock::m_time_counter = {std::chrono::nanoseconds}

instead of eg

system_clock::m_time_counter = 133ns

That forces me to expand the field everytime and dig into the type to reveal the __r member that holds the std::chrono::duration<long, std::ratio>::rep value I am interested in. I am on ubuntu 20.04, using gdb 10.2

I am open to using any gdb pretty printers (python version welcome) - and want to make sure I am not missing any implementation out there so I don't reinvent the wheel.

I ended up adding a.gdbinit file in my home directory with a few lines of python which achieves the single-line value display I was after.

python # way to tell .gdbinit we enter a python section
import gdb
class ChronoPrinter:

    def __init__(self, val):
        self.val = val

    def to_string(self):
        integral_value = self.val['__r']
        return f"{integral_value}"

p = gdb.printing.RegexpCollectionPrettyPrinter("sp")
p.add_printer("chrono", "^std::chrono::duration<.*>$", ChronoPrinter)
o = gdb.current_objfile()
gdb.printing.register_pretty_printer(o, p)
end # end of python section

I then get the pretty view:

system_clock::m_time_counter = {std::chrono::nanoseconds} 33

Note: The libstdc++ gdb printers from the repo mentioned there https://sourceware.org/gdb/wiki/STLSupport seem to be affecting only the dislayed type name (eg turn std::chrono::duration<long, std::ratio> into the more friendly std::chrono::nanoseconds). A useful command to list enabled printers in a gdb session is:

info pretty-printers

The output under libstdc++-v6 doesn't have anything related to chrono.

> objfile /lib/x86_64-linux-gnu/libstdc++.so.6 pretty-printers:  
> libstdc++-v6
>     __gnu_cxx::_Slist_iterator
>     __gnu_cxx::__8::_Slist_iterator
>     __gnu_cxx::__8::__normal_iterator
>     __gnu_cxx::__8::slist
>     __gnu_cxx::__normal_iterator
... /*many more but nothing chrono related */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM