[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

相关推荐
Nebula嵌入式5 小时前
【C语言】09-深入解析main函数
linux·c语言·开发语言·嵌入式
Dxy12393102166 小时前
Linux 编译安装 Python 3.12.10(多版本共存,不破坏系统Python)
linux·运维·python
xz驱动分享7 小时前
Linux DMA 子系统学习笔记
linux·dma·rk3588·嵌入式软件
w67820078 小时前
Prisma不能优雅的支持DTO,试试Vona ORM吧
linux·运维·ubuntu
Darkwanderor9 小时前
Linux系统编程实战项目:模拟实现shell
linux·c++
杨某不才10 小时前
如何能让Linux服务器对shell 终端 + sftp 文件传输长期保活
linux·运维·服务器
vance0410 小时前
免费Cloudflare隧道隐藏公网IP
linux·tcp/ip·github
杨云龙UP11 小时前
生产环境Oracle表空间扩容实战:使用Toad for Oracle图形界面新增Datafile(ASM+OMF)
linux·运维·数据库·oracle·表空间·asm 存储管理·toad
三言老师11 小时前
文本工具组合统计服务器日志数据
linux·运维·服务器
mounter62512 小时前
认识 Tetragon:基于 eBPF 的安全监控与强制执行工具
linux·ebpf·cve·kernel