C++错误:对'clock_gettime'和'clock_settime'的未定义引用

nas*_*ski 153 c++ linux ubuntu posix time.h

我对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;
}
Run Code Online (Sandbox Code Playgroud)

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

Dmi*_*kov 277

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

  • 尝试项目 - >构建选项 - >链接器设置; 然后添加库rt (7认同)
  • @puk尝试在`main.cpp`之后放置`-lrt` - 共享库的顺序很重要 - 参见[this](http://stackoverflow.com/a/12272890/279308)或[that](http:// stackoverflow .com/a/5571596/279308)了解更多详情 (4认同)
  • 很抱歉在这个关节中没有它,但你可以在一个完整的例子中使用它,像`g ++ -o main -lrt main.cpp`之类的东西对我来说不起作用 (3认同)

小智 42

例:

c++ -Wall filefork.cpp -lrt -O2
Run Code Online (Sandbox Code Playgroud)

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

一些旧gcc版本并不关心这个位置.

  • 谢谢你,`-lrt`没有处于正确的位置让我头疼.对于这种疯狂(好吧,很多人说是犯罪)的设定,是否有任何动机? (9认同)

小智 26

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

一个单独的论坛帖子建议-lrt在项目对象文件之后需要.移动-lrt到命令的末尾为我解决了这个问题,虽然我不知道为什么的细节.

  • 从ircnet引用twkm:链接器仅维护所需的符号列表.一旦搜索了文件的符号,只保留它所需要的内容,它提供的内容将被丢弃并移动到下一个文件名.所以从左到右,但非常健忘. (6认同)

P.P*_*.P. 26

由于glibc 2.17,-lrt不再需要库链接.

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.
Run Code Online (Sandbox Code Playgroud)

如果您决定升级glibc,那么您可以检查glibc兼容性跟踪器,如果您担心使用较新的glibc是否会出现任何问题.

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

ldd --version
Run Code Online (Sandbox Code Playgroud)

(当然,你使用旧的glibc(<2.17),然后你仍然需要-lrt.)