[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

相关推荐
三千里31 分钟前
ZSH的简单配置
linux·zsh·terminal
提伯斯6461 小时前
解决Fast-Drone-250编译相关错误
linux·ros·无人机·fast-drone
liulilittle1 小时前
过冲:拥塞控制的呼吸与盲行
linux·网络·c++·tcp/ip·计算机网络·tcp·通信
无足鸟ICT2 小时前
【RHCA+】三种工作模式
linux
Dlrb12112 小时前
Linux系统编程-会话、守护进程与系统日志
linux·守护进程·会话·进程组·系统日志
赵民勇2 小时前
Linux strings命令详解
linux·运维
GongzZz2 小时前
Linux 内存分配差异:用户空间 vs 内核空间
linux
敲代码的瓦龙2 小时前
操作系统?Android与Linux!!!
android·linux·运维
xiaoye-duck2 小时前
《Linux系统编程》Linux 进程信号深度解析(上):信号的产生方式、本质和闹钟
linux
Dxy12393102163 小时前
BAT 窗口不输出日志:三种静默方案,从半隐藏到完全消失
linux·运维·服务器