5

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;

}
Yunnosch
  • 26,130
  • 9
  • 42
  • 54
appendix
  • 119
  • 1
  • 2
  • 8
  • Well the problem is probably in your makefile, not in your code. – john Jan 23 '18 at 21:18
  • What platform are you trying to compile this application for? –  Jan 23 '18 at 21:18
  • 1
    If you're on linux, you probably forgot the `-lrt` on your link command (which should have been included in your question). [Closely related question here](https://stackoverflow.com/questions/31147129/undefined-reference-to-shm-open-using-cmake). – WhozCraig Jan 23 '18 at 21:19
  • You have to use the `-lrt` link option. – Pablo Jan 23 '18 at 21:19
  • says so right there in the man page http://man7.org/linux/man-pages/man3/shm_open.3.html – pm100 Jan 23 '18 at 21:22

1 Answers1

13

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.

Rob K
  • 8,757
  • 2
  • 32
  • 36