Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined reference to 'shm_open'

I'm trying to make a simple communicator, using shared memory.

It should be able to write some text and save it in shared memory.

Could someone explain to me why I get error:

undefined reference to `shm_open'
collect2: error: ld returned 1 exit status

I was trying to create Makefile for both programs to compile, but I still get errors.

This is the code I'm working with right now:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <errno.h>

#define TEXT_SIZE 512

int i;

struct shared_data
{
  int data;
  char some_text[TEXT_SIZE];
};


int main()
{
  struct shared_data *ptr;
  const char *shm_name = "comunicator";
  int shm_fd;
  shm_fd = shm_open(shm_name, O_CREAT | O_RDWR, 0666);

  ftruncate(shm_fd, sizeof(struct shared_data));

  ptr = mmap(0, sizeof(struct shared_data), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
  if (ptr == MAP_FAILED) {
    printf("mmap - failed.\n");
    return -1;
  }

ptr->data = 0;

for(i=0; i<10; i++)
{
        while(ptr->data == 1) sleep(1);
        scanf("%s", ptr->some_text);
        ptr->data = 1;
}



  ptr->data = 0;
  sleep(10);
sprintf(ptr->some_text,"Jakis tekst");
 ptr->data = 1;

 sleep(10);

  if (munmap(ptr, sizeof(struct shared_data)) == -1) {
   printf("unmap failed: %s\n", strerror(errno));
   exit(1);
 }

 if (close(shm_fd)) {
   printf("close failed: %s", strerror(errno));
    exit(1);
  }

  return 0;

}
like image 470
appendix Avatar asked Jan 03 '23 22:01

appendix


1 Answers

You aren't linking the library where it's defined in your link stage.

http://man7.org/linux/man-pages/man3/shm_open.3.html

Link with -lrt

ETA Generally, if you see an "undefined reference to X" error from the compiler, you've forgotten to link in the library where it's defined.

like image 111
Rob K Avatar answered Jan 05 '23 16:01

Rob K