You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用GCC编译时出现memrchr未定义引用错误的求助

解决MinGW64下memrchr函数未定义引用问题

问题背景

在MSYS2构建的GCC 12.2.0环境中,尝试使用GNU扩展函数memrchr,已定义_GNU_SOURCE并引入<string.h>头文件,但编译时出现隐式声明和链接错误。

环境与报错信息

GCC版本信息

> gcc --version
gcc.exe (Rev6, Built by MSYS2 project) 12.2.0
Copyright (C) 2022 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

最小复现代码

#define _GNU_SOURCE

#include <string.h>

int main() {
    memrchr("hello", 'l', 5);
}

编译报错详情

> gcc .\src\temp.c
.\src\temp.c: In function 'main':
.\src\temp.c:6:9: warning: implicit declaration of function 'memrchr'; did you mean 'memchr'? [-Wimplicit-function-declaration]
    6 |         memrchr("hello", 'l', 5);
      |         ^~~~~~~
      |         memchr
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\SOURAV~1\AppData\Local\Temp\ccodiFYq.o:temp.c:(.text+0x23): undefined reference to `memrchr'
collect2.exe: error: ld returned 1 exit status

解决方案

1. 手动实现memrchr函数

MinGW64的C运行时库未提供memrchr的官方实现,可自行编写兼容版本添加到代码中:

#define _GNU_SOURCE

#include <string.h>
#include <stddef.h>

void* memrchr(const void* s, int c, size_t n) {
    const unsigned char* ptr = (const unsigned char*)s + n;
    while (n-- > 0) {
        if (*(--ptr) == (unsigned char)c) {
            return (void*)ptr;
        }
    }
    return NULL;
}

int main() {
    memrchr("hello", 'l', 5);
}

2. 切换到MSYS2的UCRT64或MSYS环境

  • UCRT64环境:使用微软Universal C Runtime,对GNU扩展支持更完善,打开UCRT64终端后直接编译代码即可正常使用memrchr。
  • MSYS环境:基于glibc,原生支持所有GNU扩展函数,无需额外配置。

3. 尝试链接libgnu库

部分MinGW版本提供libgnu库,包含GNU扩展函数实现,编译时添加-lgnu参数:

gcc .\src\temp.c -lgnu

内容的提问来源于stack exchange,提问作者Sourav Kannantha B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 04:15:51