c - 对 'shm_open' 的 undefined reference

标签 c linux shared-memory

我正在尝试使用共享内存制作一个简单的通信器。

它应该能够写入一些文本并将其保存在共享内存中。

有人可以向我解释为什么会出现错误:

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

我试图为两个程序创建 Makefile 进行编译,但我仍然遇到错误。

这是我现在正在使用的代码:

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

}

最佳答案

您没有链接在链接阶段定义的库。

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

链接-lrt

ETA 通常,如果您从编译器中看到“对 X 的 undefined reference ”错误,则您忘记了在定义它的库中进行链接。

关于c - 对 'shm_open' 的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48410966/

相关文章:

python 多处理和 mmap

c# - 如何在 C 中初始化多维字符数组?

c - 信号量锁排队机制?

c - 在 C 中定义类似函数的宏时,使用 {} 对或 () 对有什么区别吗?

python - 在没有 sudo 的情况下使用 apt-get/yum

将结构数组复制到共享内存中

在printf语句中调用c函数?

python - 关闭缓冲

Linux 内核编译错误 Unsupported NR_CPUS for lb tracepoint

c - 通过客户端服务器方法写入和读取共享内存以获取数字的平方