2010-03-10 86 views
136

我对Ubuntu很新,但我似乎无法得到它的工作。它在我的学校电脑上工作正常,我不知道我没有做什么。我检查了usr/include和time.h是否还好。这里是代码:Ubuntu Linux C++错误:未定义的引用'clock_gettime'和'clock_settime'

#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来构建和运行。任何帮助将是伟大的,谢谢。

回答

250

-lrt添加到g ++命令行的末尾。这个链接在librt.so“Real Time”共享库中。

+0

这工作,如果我手动编译 - 任何想法如何自动化在codeblocks? – naspinski 2010-03-10 15:41:44

+7

尝试项目 - >构建选项 - >链接器设置;然后添加库rt – 2010-03-10 15:55:11

+0

你的建议对我来说工作正常..我是'C'的新手......'-lrt'do是什么? – noufal 2013-10-10 06:42:24

26

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

单独的论坛帖子建议-lrt需要在项目对象文件之后。 将-lrt移到该命令的末尾,为我解决了这个问题,但我不知道为什么。

+1

你能发布一个链接到论坛主题吗? – 2011-11-10 11:31:27

+5

从ircnet引用twkm: 链接器仅维护所需的符号列表。一旦文件符号被搜索完毕,只保留它需要的内容,丢弃它提供的内容并移动到下一个文件名。 所以从左到右,但很健忘。 – domen 2012-03-07 06:52:11

41

例如:

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

对于gcc版本4.6.1,-lrt必须filefork.cpp否则你得到一个链接错误。

一些年纪较大的gcc版本并不在意位置。

+9

谢谢你,'-lrt'不在正确的位置上让我头痛。有没有这种疯狂的动机(呃,很多人说犯罪)? – Avio 2012-07-30 11:40:24

+0

@Avio - 由于历史原因,订单很重要。编译器用于按顺序处理每个参数。因为库是“软”引用,与'* .o'参数中的“硬”引用相反,所以库函数被忽略*除非*它们是先前引用的,也就是说,在左边。 – 2014-10-02 21:56:50

23

由于glibc 2.17,链接-rt的库不再需要。

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的,那么你可以检查compatibility tracker of glibc如果您担心是否会有使用较新的任何问题glibc的。

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

ldd --version 

(当然,您使用的是老的glibc(< 2.17),那么您将仍然需要-lrt

+1

确实是正确的信息,非常有用 – cpp11dev 2016-10-26 04:09:21