clock_gettime()在PC上运行良好,但在服务器上它会中止编译

Lak*_*ith 3 c linux ubuntu gcc pthreads

我使用以下函数来获取多线程程序的执行时间:

clock_gettime(CLOCK_MONOTONIC,&start);
/*
******PROGRAM CODE*************
*/

clock_gettime(CLOCK_MONOTONIC,&end);
Run Code Online (Sandbox Code Playgroud)

它在我的运行ubuntu 14.04的PC笔记本电脑上工作正常,但是当我尝试在服务器上编译并运行它时,编译失败导致错误.

在我的电脑上:

laksith@laksithPC:~/Desktop/test$ gcc main_v8.c -lpthread
laksith@laksithPC:~/Desktop/test$ ./a.out
Run Code Online (Sandbox Code Playgroud)

在服务器上:

[laksith@gca test_run]$ gcc main_v8.c -lpthread
/tmp/ccyMMmx.o:In function 'main':
main_v8.c:(.text+0x21):undefined reference to 'clock_gettime'
main_v8.c:(.text+0x182):undefined reference to 'clock_gettime'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

有人可以帮帮我吗?

Pau*_*l R 7

这只是一个链接错误 - 你需要链接librt- 更改:

gcc main_v8.c -lpthread
Run Code Online (Sandbox Code Playgroud)

至:

gcc -Wall main_v8.c -lpthread -lrt
Run Code Online (Sandbox Code Playgroud)

请注意,Linux手册页中介绍了以下内容clock_gettime:

NAME clock_getres,clock_gettime,clock_settime-时钟和时间函数

概要 #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);
Run Code Online (Sandbox Code Playgroud)

与-lrt链接.

请注意,较新版本的glibc(> = 2.17)不再需要链接librt,这可能解释了为什么您不需要-lrt在PC上添加Ubuntu 14版本.

  • Upvote解释了为什么在第一种情况下没有错误 (2认同)