165

我对 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 来构建和运行。任何帮助都会很棒,谢谢。

4

4 回答 4

296

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

于 2010-03-10T15:38:57.717 回答
44

例子:

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

对于gcc4.6.1 版本,-lrt必须 filefork.cpp之后,否则会出现链接错误。

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

于 2011-11-11T01:48:23.113 回答
33

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

现在clock_*是主 C 库的一部分。您可以查看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 的兼容性跟踪器,如果您担心使用较新的 glibc 是否会出现任何问题。

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

ldd --version

(当然,如果你使用旧的 glibc (<2.17) 那么你仍然需要-lrt.)

于 2015-09-18T10:05:51.687 回答
27

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

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

于 2011-11-10T10:53:42.013 回答