0

It was once mentioned that call printf and call exit, for example, are both calls to actual subroutines, just like those had to make for CO Lab. This got me wondering: where are these subroutines located, are they written in the same syntax/assembly as well and can we actually take a look at them as if we were looking at our own subroutines?

Assignment 5B (make your own printf) explains that these are from some sort of (C, if I remember correctly) library and therefore we used GCC, but I am not sure if I fully understood what this means and how it works.

  • Sure, of course, you can single-step into the call to it in GDB. It's pretty complicated, though, with layers of wrapper functions to avoid redundant implementations for printf, sprintf, fprintf, vfprintf, and so on. And printf format strings are *not* simple, e.g. a `%2$n` conversion can take arg 2 as a pointer and store the number of characters printed so far into that int. https://man7.org/linux/man-pages/man3/printf.3.html Plus it has to handle various I/O buffering situations (full, line, or unbuffered). A toy implementation might just format and `write` – Peter Cordes Oct 10 '20 at 07:21
  • So really you'd probably have better luck looking at the glibc source code if you really want to see the implementation. (The `2$` positional-arg stuff is POSIX / SuS, not ISO C, and note it can be used with any conversion. But highly likely your assignment isn't intended to cover that complexity, and maybe not field-width / precision. https://en.cppreference.com/w/c/io/fprintf). For the printing-integers part, see [Printing an integer as a string with AT&T syntax, with Linux system calls instead of printf](https://stackoverflow.com/q/45835456) – Peter Cordes Oct 10 '20 at 07:22
  • 1
    And BTW, if you do want to step into it in GDB, step into the 2nd call, or compile with `-fno-plt` so you aren't stepping into lazy dynamic linking. ([Step into standard library call with godbolt](https://stackoverflow.com/q/56245402)) – Peter Cordes Oct 10 '20 at 07:47
  • 1
    On Linux, `printf` is coded in C (and known to [GCC](http://gcc.gnu.org)...). Read source code of [GNU libc](https://www.gnu.org/software/libc/) or of [musl-libc](http://musl.libc.org/) – Basile Starynkevitch Oct 10 '20 at 07:51
  • Thanks for the help guys! Now I knew what terms I had to Google for I also found this lengthy explanation: [link](https://stackoverflow.com/questions/56245402/step-into-standard-library-call-with-godbolt?noredirect=1&lq=1). And indeed, as you guys also mentioned, it's a lot more work than I initially thought and goes way above my level of understanding. Once again thanks anyway though! –  Oct 10 '20 at 08:03

0 Answers0