Mac M2运行含zergon321/reisen的Go代码时ld找不到-lavutil
Mac M2运行依赖reisen的Go代码:链接错误排查与解决
问题场景
在Mac M2设备上运行引入github.com/zergon321/reisen的Go代码时,执行命令:
CGO_CPPFLAGS="-I/opt/homebrew/Cellar/ffmpeg/5.1.2/include" go run .
得到输出:
# github.com/zergon321/reisen cgo-gcc-prolog:114:35: warning: 'swr_alloc_set_opts' is deprecated [-Wdeprecated-declarations] /opt/homebrew/Cellar/ffmpeg/5.1.2/include/libswresample/swresample.h:259:1: note: 'swr_alloc_set_opts' has been explicitly marked deprecated here /opt/homebrew/Cellar/ffmpeg/5.1.2/include/libavutil/attributes.h:100:49: note: expanded from macro 'attribute_deprecated' /usr/local/go/pkg/tool/darwin_arm64/link: running clang failed: exit status 1 ld: library not found for -lavutil clang: error: linker command failed with exit code 1 (use -v to see invocation)
已知上下文:
- 已解决之前找不到
libavcodec/avcodec.h的头文件问题 - libavutil与libavcodec安装在同一位置
/opt/homebrew/Cellar/ffmpeg/5.1.2/include
疑问解答
这个错误和libavutil的弃用警告完全无关。弃用警告只是编译阶段的提示,仅说明代码中使用的函数已被标记为过时,不会导致编译或链接失败;真正导致运行失败的是链接阶段的错误:ld: library not found for -lavutil——链接器找不到libavutil的二进制库文件(.dylib或.a)。
解决方法
你仅设置了头文件的搜索路径(CGO_CPPFLAGS),但未告知链接器FFmpeg库文件的位置,需要补充相关参数:
方法1:手动指定库路径与链接库
- 确认FFmpeg库文件位置:
/opt/homebrew/Cellar/ffmpeg/5.1.2/lib目录下存在libavutil.dylib等库文件 - 修改运行命令,添加
CGO_LDFLAGS参数:
CGO_CPPFLAGS="-I/opt/homebrew/Cellar/ffmpeg/5.1.2/include" CGO_LDFLAGS="-L/opt/homebrew/Cellar/ffmpeg/5.1.2/lib -lavutil -lavcodec -lavformat -lswresample" go run .
注:可根据reisen实际依赖的FFmpeg库调整后面的库名称,比如按需添加-lavfilter等。
方法2:使用pkg-config自动获取参数
借助Homebrew提供的pkg-config工具自动生成编译和链接参数,更简便:
PKG_CONFIG_PATH="/opt/homebrew/Cellar/ffmpeg/5.1.2/lib/pkgconfig" go run .
pkg-config会自动读取FFmpeg的配置文件,将头文件路径、库路径及依赖库参数传递给CGO。
内容的提问来源于stack exchange,提问作者Ido Van Orell
相关产品推荐
相关产品推荐

