[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

相关推荐
Jia ming12 分钟前
从打补丁到一行配置:PREEMPT_RT 主线化之后,实时内核到底该怎么配?
linux
杨云龙UP14 分钟前
MySQL Host is blocked because of many connection errors 导致 JDBC 连接失败排查与解决
linux·运维·网络·数据库·sql·mysql·登录失败
企鹅的蚂蚁1 小时前
LubanCat RK3588 实时 Linux 开发(九):从 U-Boot 到 initramfs 的串口启动故障分析
linux·rk3588·u-boot·串口调试·initramfs·linux启动
kkkkkkkkkk_Z1 小时前
学嵌入式和Linux应用编程|学习日记:UDP协议与Wireshark抓包学习笔记
linux·笔记·学习
嵌入式小能手2 小时前
飞凌嵌入式ElfBoard-Shell编程应用实例-提取字符并设置rtc时间
linux
刃神太酷啦2 小时前
Redis 核心进阶:哨兵、集群、缓存问题与分布式锁详解----《Hello Redis!》(6)
linux·c语言·数据库·c++·redis·分布式·缓存
大卡片2 小时前
LCD相关知识
linux
闲云野鹤在人间2 小时前
Docker入门|第3章 镜像详解
linux·网络·docker·容器·centos·云计算·php
小卿噢2 小时前
malloc 成功 ≠ 你有内存:一次把 OOM 从头测到尾
linux·后端
团子股股东峥哥2 小时前
day38-RHEL-管理存储堆栈
linux·运维·服务器