clock_gettime函数

2021-07-21, updated 2021-09-12

#include <time.h>

int clock_getres(clockid_t clk_id, struct timespec *res);
int clock_gettime(clockid_t clk_id, struct timespec *tp);
int clock_settime(clockid_t clk_id, const struct timespec *tp);

// Link with -lrt.

参数

struct timespec {
    time_t   tv_sec;        /* seconds */
    long     tv_nsec;       /* nanoseconds */
};

示例

void oalTms_get(CmsTimestamp *tms)
{
   struct timespec ts;
   SINT32 rc;

   if (tms == NULL)
   {
      return;
   }

   rc = clock_gettime(CLOCK_MONOTONIC, &ts);
   if (rc == 0)
   {
      tms->sec = ts.tv_sec;
      tms->nsec = ts.tv_nsec;
   }
   else
   {
      cwmp_log_error("clock_gettime failed, set timestamp to 0");
      tms->sec = 0;
      tms->nsec = 0;
   }
}

问题

undefined reference to clock_gettime

发现是在链接的时候出错。经过查找发现clock_gettime在实时库librt(real time)里面,由于链接的时候没有链接这个库导致报错。

解决思路:

只需在我们运行的Makefile文件里面添加动态链接库librt ( -lrt ) ,重新编译即可。

words: 390 tags: language c