[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

相关推荐
小白同学_C1 天前
Lab4-Lab: traps && MIT6.1810操作系统工程【持续更新】 _
linux·c/c++·操作系统os
今天只学一颗糖1 天前
1、《深入理解计算机系统》--计算机系统介绍
linux·笔记·学习·系统架构
不做无法实现的梦~1 天前
ros2实现路径规划---nav2部分
linux·stm32·嵌入式硬件·机器人·自动驾驶
默|笙1 天前
【Linux】fd_重定向本质
linux·运维·服务器
陈苏同学1 天前
[已解决] Solving environment: failed with repodata from current_repodata.json (python其实已经被AutoDL装好了!)
linux·python·conda
“αβ”1 天前
网络层协议 -- ICMP协议
linux·服务器·网络·网络协议·icmp·traceroute·ping
不爱学习的老登1 天前
Windows客户端与Linux服务器配置ssh无密码登录
linux·服务器·windows
十日十行1 天前
修复root用户登录的浏览器无法跳转vscode问题
ubuntu
小王C语言1 天前
进程状态和进程优先级
linux·运维·服务器
xlp666hub1 天前
【字符设备驱动】:从基础到实战(下)
linux·面试