2010-03-10 183 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