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

Ubuntu20.04下g++编译找不到libavcodec但gcc可正常编译的问题

解决g++编译libav代码出现未定义引用的问题

问题场景

  • 系统环境:Ubuntu 20.04
  • 示例代码(main.c):
#include <libavcodec/avcodec.h>

int main()
{
    avcodec_find_encoder((enum AVCodecID) 0);
    return 0;
}
  • 异常现象:用gcc main.c -lavcodec编译可正常通过,但执行g++ main.c -lavcodec时出现链接错误:
/usr/bin/ld: /tmp/ccHxMTp1.o: in function `main':
test.c:(.text+0xe): undefined reference to `avcodec_find_encoder(AVCodecID)'
collect2: error: ld returned 1 exit status

问题原因

libav是纯C开发的库,C编译器会对函数名进行名字修饰(Name Mangling),生成带有额外信息的符号名;而gcc编译的C库导出的是未经修饰的C风格符号,导致g链接时无法匹配到对应函数符号。

解决方法

修改代码,用extern "C"包裹libav的头文件,告诉C++编译器按照C的规则处理这些头文件中的函数声明:

extern "C" {
#include <libavcodec/avcodec.h>
}

int main()
{
    avcodec_find_encoder((enum AVCodecID) 0);
    return 0;
}

修改后再执行g++ main.c -lavcodec即可正常编译链接。

部分新版本的libav头文件内部已包含extern "C"的条件编译逻辑,但Ubuntu 20.04自带的版本可能未适配,手动包裹是更稳妥的方案。


内容的提问来源于stack exchange,提问作者Jack M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:15:39