【问题标题】:C++ error: undefined reference to 'clock_gettime' and 'clock_settime'C++ 错误:未定义对“clock_gettime”和“clock_settime”的引用
【发布时间】:2011-01-25 23:10:09
【问题描述】:

我对 Ubuntu 很陌生,但我似乎无法让它工作。它在我的学校计算机上运行良好,我不知道我没有在做什么。我已经检查了 usr/include 和 time.h 就可以了。代码如下:

#include <iostream>
#include <time.h>
using namespace std;

int main()
{
    timespec time1, time2;
    int temp;
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
    //do stuff here
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
    return 0;
}

我也使用 CodeBlocks 作为我的 IDE 来构建和运行。任何帮助都会很棒,谢谢。

【问题讨论】:

标签: c++ linux ubuntu posix time.h


【解决方案1】:

-lrt 添加到 g++ 命令行的末尾。此链接在 librt.so“实时”共享库中。

【讨论】:

  • 如果我手动编译就可以了——知道我是如何在代码块中自动化的吗?
  • 尝试项目 -> 构建选项 -> 链接器设置;然后添加库 rt
  • 你的建议对我来说很好。我是C的新手...-lrt做什么?
  • 很抱歉在这个联合中使用它,但是你能在一个完整的例子中使用它吗,像 g++ -o main -lrt main.cpp 这样的东西对我不起作用
  • @puk 尝试将 -lrt 放在 main.cpp 之后 - 共享库的顺序很重要 - 请参阅 thisthat 了解更多详情
【解决方案2】:

示例:

c++ -Wall filefork.cpp -lrt -O2

对于gcc 4.6.1 版,-lrt 必须在之后 filefork.cpp 否则会出现链接错误。

一些较旧的gcc 版本不关心位置。

【讨论】:

  • 谢谢,-lrt 位置不对让我头疼。这种疯狂(好吧,很多人说是犯罪)的设置有什么动机吗?
  • @Avio - 由于历史原因,订单很重要。编译器过去只是按顺序处理每个参数。因为库是“软”引用,而不是 *.o 参数中的“硬”引用,所以库函数被忽略除非它们之前被引用过,也就是说,在左边。
【解决方案3】:

从 glibc 2.17 版开始,不再需要链接 -lrt 的库。

clock_* 现在是主 C 库的一部分。您可以看到完成此更改的change history of glibc 2.17 解释了此更改的原因:

+* The `clock_*' suite of functions (declared in <time.h>) is now available
+  directly in the main C library.  Previously it was necessary to link with
+  -lrt to use these functions.  This change has the effect that a
+  single-threaded program that uses a function such as `clock_gettime' (and
+  is not linked with -lrt) will no longer implicitly load the pthreads
+  library at runtime and so will not suffer the overheads associated with
+  multi-thread support in other code such as the C++ runtime library.

如果您决定升级 glibc,如果您担心使用较新的 glibc 是否会出现任何问题,可以查看compatibility tracker of glibc

要检查系统上安装的 glibc 版本,请运行以下命令:

ldd --version

(当然,如果你使用旧的 glibc (-lrt。)

【讨论】:

    【解决方案4】:

    我遇到了同样的错误。我的链接器命令确实包含包含-lrt 的rt 库,这是正确的并且它工作了一段时间。重新安装 Kubuntu 后它停止工作。

    一个单独的论坛帖子建议在项目目标文件之后需要-lrt。 将-lrt 移到命令末尾为我解决了这个问题,尽管我不知道具体原因。

    【讨论】:

    • 从 ircnet 引用 twkm:链接器只维护所需的符号列表。一旦文件的符号被搜索,只保留它需要的,它提供的将被丢弃,并移动到下一个文件名。从左到右,但很健忘。
    最近更新 更多