我刚刚遇到系统崩溃并重新安装Ubuntu 11.10,我的代码产生了这个奇怪的错误。
我写了一个简单的代码示例来测试问题所在:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
int main (void) {
int i;
i = shm_open ("/tmp/shared", O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); printf ("shm_open rc = %d\n", i);
shm_unlink ("/tmp/shared");
return (0);
}
并且编译命令是
gcc -lrt test.c -o test
错误是:
/tmp/ccxVIUiP.o: In function `main':
test.c:(.text+0x21): undefined reference to `shm_open'
test.c:(.text+0x46): undefined reference to `shm_unlink'
collect2: ld returned 1 exit status
我已经添加了-lrt lib,为什么它仍然没有编译?
答案 0 :(得分:51)
最后的图书馆:
gcc test.c -o test -lrt
-llibrary -l library Search the library named library when linking. (The second alternative with the library as a separate argument is only for POSIX compliance and is not recommended.) It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, `foo.o -lz bar.o' searches library `z' after file foo.o but before bar.o. If bar.o refers to functions in `z', those functions may not be loaded.
答案 1 :(得分:5)
从
更改编译行gcc -lrt test.c -o test
到
gcc test.c -o test -lrt
答案 2 :(得分:4)
在Expert C programming
页面108:
<Handy Heuristic>
Where to Put Library Options:Always put the -l library options at the rightmost end of your compilation command line.
但它没有说明原因,所以我想这有点规律?:)
答案 3 :(得分:0)
对于像我一样使用超级自动魔法 CMAKE 的人,请尝试添加:
target_link_libraries(your_binary_name PRIVATE librt.so)
到您的CMakeLists.txt
或者,根据需要将 PRIVATE 替换为 PUBLIC..
如果您已经建立了良好的库路径(例如,/usr/lib 中所有需要的库),您可能只需在 CMakeLists.txt 中声明即可:
set(CMAKE_CXX_FLAGS "-lrt")