Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined reference to `shm_open' even while compiling with -pthread -lrt

Tags:

c

gcc

I see a similar question has been asked with no coherent solution. Using the gcc compiler on linux, I get the message:

/tmp/ccPNsJFZ.o: In function `main':
testChTh.c:(.text+0xbfb): undefined reference to `shm_open'
collect2: error: ld returned 1 exit status

after typing gcc -pthread -lrt -o testChTh testChTh.c into the command line. I only use shm_open once in my code, which is:

int shm_fd;

  /* create the shared memory segment */
  shm_fd = shm_open(name, O_RDWR, 0666);

I have the following relevant libraries included:

#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>

Any insight is much appreciated!

like image 346
Spencer Goff Avatar asked Mar 27 '17 16:03

Spencer Goff


1 Answers

In your case

  gcc -pthread -lrt -o testChTh testChTh.c

is not going to work, as you are providing testChTh.c at last which expects to use librt. You need to write like

 gcc -o testChTh testChTh.c -pthread -lrt

Quoting the online manual (emphasis mine)

-l library

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 135
Sourav Ghosh Avatar answered Sep 28 '22 03:09

Sourav Ghosh