Undefined ссылка 'shm_open', уже добавьте флаг -lrt здесь
У меня просто сбой системы и переустановка 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, почему он еще не компилируется?
Ответы
Ответ 1
Библиотеки в конце:
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.
Ответ 2
В Expert C programming
Page 108:
<Handy Heuristic>
Where to Put Library Options:Always put the -l library options at the rightmost end of your compilation command line.
Но это не говорит, почему, так что я думаю, что это несколько правило?:)
Ответ 3
Измените строку компиляции из
gcc -lrt test.c -o test
к
gcc test.c -o test -lrt