Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined reference 'shm_open', already add -lrt flag here

Tags:

c

linux

I just have a system crash and reinstall Ubuntu 11.10, and my code produces this strange error.

I wrote a simple code sample to test where the problem is:

#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); } 

and the compile command is

gcc -lrt test.c -o test

The error is:

/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 

I have already added -lrt lib, why does it still not compile?

like image 442
bxshi Avatar asked Mar 29 '12 10:03

bxshi


2 Answers

Libraries at the end:

gcc test.c -o test -lrt

From GCC Link Options:

 -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. 
like image 119
hmjd Avatar answered Sep 18 '22 02:09

hmjd


Change the compile line from

gcc -lrt test.c -o test 

to

gcc test.c -o test -lrt 
like image 27
codaddict Avatar answered Sep 18 '22 02:09

codaddict