Search code examples
cfunctiongccglibc

What way can code be written so libraries don't need to be called in C?


I'm exploring high-precision time functions in C. I came across clock_gettime and read about it here:

http://man7.org/linux/man-pages/man2/clock_gettime.2.html

I notice it says:

 Link with -lrt (only for glibc versions before 2.17).

I wonder why I can use lower-precision time functions without needing to add anything to my gcc compile line? Is there a way for me to use the high-precision code differently so I don't need to add anything on my compile line?

I understand my system is using an old....old version of glibc, which is why I have to do this in my case, but I'm asking for the sake of those (such as myself) who are unable to update glibc.

Code in progress:

#include <stdio.h>
#include <time.h>

int main(int argc, char **argv)
{

  int result;
  struct timespec tp;
  clockid_t clk_id;

//  clk_id = CLOCK_REALTIME;
  clk_id = CLOCK_MONOTONIC;
//  clk_id = CLOCK_BOOTTIME;
//  clk_id = CLOCK_PROCESS_CPUTIME_ID;

  // int clock_gettime(clockid_t clk_id, struct timespec *tp);
  result = clock_gettime(clk_id, &tp);
  printf("result: %i\n", result);
  printf("tp.tv_sec: %lld\n", tp.tv_sec);
  printf("tp.tv_nsec: %ld\n", tp.tv_nsec);

  result = clock_getres(clk_id, &tp);
  printf("result: %i\n", result);
  printf("tp.tv_sec: %lld\n", tp.tv_sec);
  printf("tp.tv_nsec: %ld\n", tp.tv_nsec);

}

Solution

  • The functions that you can call without mentioning a library are located in libc. The -lc option to link to this library is silently added for you.

    To call functions in other libraries, you must add the corresponding -l (and possibly -L) option to your linking command. This is normal, and you shouldn't feel like this means something is wrong.

    There is no rational explanation for which functions are included in libc and which ones aren't. It's just historical accident. Just be thankful to the nice people who write the man pages for putting the necessary linker options are right their at the top of the page so you don't have to hunt for them.