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

标签 c linux ubuntu gcc pthreads

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

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

clock_gettime(CLOCK_MONOTONIC,&end);

它在我运行 ubuntu 14.04 的 PC 笔记本电脑上运行良好,但是当我尝试在服务器上编译和运行它时,编译失败并出现错误。

在我的笔记本电脑上:

laksith@laksithPC:~/Desktop/test$ gcc main_v8.c -lpthread
laksith@laksithPC:~/Desktop/test$ ./a.out

在服务器上:

[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

有人可以帮我吗?

最佳答案

这只是一个链接错误 - 您需要链接 librt - 改变:

gcc main_v8.c -lpthread

到:

gcc -Wall main_v8.c -lpthread -lrt

请注意,这包含在 Linux man page for clock_gettime 中:

NAME clock_getres, clock_gettime, clock_settime - clock and time functions

SYNOPSIS #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.

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

关于clock_gettime() 在 PC 上运行良好,但在服务器上它会中止编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32602458/

相关文章:

linux - 如何使用 awk 在输入文件的最后一行之后插入新记录(行或行)?

bash - 在我的 ~/.bashrc 文件中创建 "local"别名后自动填充失败

python - 在没有 sudo 的情况下使用 GPU 在 Ubuntu 20.04 上设置 Tensorflow 2.4

Android repo 初始化失败

c - 这个c程序跳过scanf();命令并且 switch case 有错误

c - 使用预处理器在 C 中进行模板化

c - 在 HP-UX 和 Linux 上展开堆栈

python - 自定义 Python 终端不显示 Bash 提示符

c - 如何在内核源文件中包含 math.h #include <math.h>?

c - 从 c 中的函数返回二维数组时出错