[ubuntu]编译共享内存读取出现read.c:(.text+0x1a): undefined reference to `shm_open‘问题解决方案

问题log

复制代码
/tmp/ccByifPx.o: In function `main':
read.c:(.text+0x1a): undefined reference to `shm_open'
read.c:(.text+0xd9): undefined reference to `shm_unlink'
collect2: error: ld returned 1 exit status

程序代码

复制代码
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>

#define SHM_NAME "./mac_shm"
#define SHM_SIZE 18  // MAC地址长度为17个字符,加上一个终止符

int main() {
    // 打开共享内存对象
    int shm_fd = shm_open(SHM_NAME, O_RDONLY, 0666);
    if (shm_fd == -1) {
        perror("shm_open");
        exit(EXIT_FAILURE);
    }

    // 映射共享内存
    char *shm_ptr = mmap(0, SHM_SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
    if (shm_ptr == MAP_FAILED) {
        perror("mmap");
        exit(EXIT_FAILURE);
    }

    // 读取MAC地址
    printf("MAC Address: %s\n", shm_ptr);

    // 解除映射
    if (munmap(shm_ptr, SHM_SIZE) == -1) {
        perror("munmap");
        exit(EXIT_FAILURE);
    }

    // 关闭共享内存对象
    close(shm_fd);

    // 删除共享内存对象
    shm_unlink(SHM_NAME);

    return 0;
}

问题分析

编译结果实际上是说,没include相应的头文件,或是头文件不存在,man shm_open看到如下内容

解决方案

gcc shm_test.c -lrt -o shm_test

相关推荐
大聪明-PLUS14 分钟前
面向开发者的实用 GNU/Linux 命令(第二部分)
linux·嵌入式·arm·smarc
sorry#5 小时前
top简单使用
linux·运维
半壶清水5 小时前
开源免费的在线考试系统online-exam-system部署方法
运维·ubuntu·docker·开源
QQ__17646198245 小时前
Ubuntu系统创建新用户与删除用户
linux·运维·服务器
渣渣盟6 小时前
Linux邮件服务器快速搭建指南
linux·服务器·开发语言
6极地诈唬6 小时前
【PG漫步】DELETE不会改变本地文件的大小,VACUUM也不会
linux·服务器·数据库
ArrebolJiuZhou6 小时前
00 arm开发环境的搭建
linux·arm开发·单片机·嵌入式硬件
谷雨不太卷6 小时前
Linux_文件权限
linux·运维·服务器
无泪无花月隐星沉7 小时前
uos server 1070e lvm格式磁盘扩容分区
linux·运维·uos
食咗未8 小时前
Linux USB HOST EXTERNAL STORAGE
linux·驱动开发