未定义的引用'shm_open',已在此处添加-lrt标志

bxs*_*shi 34 c linux

我只是系统崩溃并重新安装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);
}
Run Code Online (Sandbox Code Playgroud)

并且编译命令是

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

我已经添加了-lrt lib,为什么它仍然没有编译?

hmj*_*mjd 54

最后的图书馆:

gcc test.c -o test -lrt

来自GCC链接选项:

-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.

  • @PavanManjunath:较新的 GCC 版本在命令行上的任何位置以任何顺序接受库。较旧的要求将它们按依赖顺序列在最后(因此任何需要“librt”的内容都位于它之前)。 (2认同)

cod*_*ict 5

从中更改编译行

gcc -lrt test.c -o test
Run Code Online (Sandbox Code Playgroud)

gcc test.c -o test -lrt
Run Code Online (Sandbox Code Playgroud)