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

| 我对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来构建和运行。任何帮助都会很棒,谢谢。     
已邀请:
-lrt
添加到g ++命令行的末尾。这链接在librt.so“实时”共享库中。     
例:
c++ -Wall filefork.cpp -lrt -O2
对于
gcc
4.6.1版,
-lrt
必须在filefork.cpp之后,否则会出现链接错误。 一些较旧的
gcc
版本并不关心这个位置。     
我遇到了同样的错误。我的链接器命令确实包含了
-lrt
这是正确的,它工作了一段时间。重新安装Kubuntu后,它停止工作。 一个单独的论坛帖子建议
-lrt
需要在项目对象文件之后。 将
-lrt
移动到命令的末尾为我解决了这个问题,虽然我不知道原因的细节。     
由于glibc 2.17,不再需要链接
-rt
的库。
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(&lt; 2.17)然后你仍然需要
-lrt
。)     

要回复问题请先登录注册