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

使用ALSA库编译C程序失败:链接器无法找到库函数

ALSA音频设备枚举程序编译时出现未定义引用错误

环境与场景

  • 设备:树莓派4,基于Debian Bullseye的树莓派OS
  • 需求:编译一个枚举音频设备的C程序,依赖ALSA库
  • 已完成操作:安装libasound、libasound2、libasound-dev包,确认libasound.so位于/usr/lib/arm-linux-gnueabihf,且所需函数存在于库中

程序代码

#include <stdio.h>
#include <stdlib.h>
#include <alsa/asoundlib.h>
#include <alsa/pcm.h>

int main() {
  int val;

  printf("ALSA library version: %s\n", SND_LIB_VERSION_STR);

  char **hints;
  /* Enumerate sound devices */
  int err = snd_device_name_hint(-1, "pcm", (void***)&hints);
  if (err != 0)
     return 0;//Error! Just return

  char** n = hints;
  while (*n != NULL) {

      char *name = snd_device_name_get_hint(*n, "NAME");

      if (name != NULL && 0 != strcmp("null", name)) {
          //Copy name to another buffer and then free it
          free(name);
      }
      n++;
  }//End of while

  //Free hint buffer
  snd_device_name_free_hint((void**)hints);
 
  return 0;
}  

编译命令与错误信息

执行编译命令:

gcc -lasound test1.c -o test1

出现错误:

/usr/bin/ld: /tmp/ccUWxojL.o: in function `main':
test1.c:(.text+0x28): undefined reference to `snd_device_name_hint'
/usr/bin/ld: test1.c:(.text+0x60): undefined reference to `snd_device_name_get_hint'
/usr/bin/ld: test1.c:(.text+0xb8): undefined reference to `snd_device_name_free_hint'
collect2: error: ld returned 1 exit status

已确认的库信息

nm -D /usr/lib/arm-linux-gnueabihf/libasound.so | grep snd_device_name*
0002f358 T snd_device_name_free_hint@@ALSA_0.9
0002f898 T snd_device_name_get_hint@@ALSA_0.9
0002f394 T snd_device_name_hint@@ALSA_0.9

解决方案

1. 调整编译命令中库的顺序

GCC链接器按从左到右的顺序处理输入文件:先处理源文件,记录所有未定义的符号;之后遇到库文件时,才会在库中查找这些未定义符号并解析。如果把库放在源文件前面,链接器处理库时还没有未定义符号,不会保留库中的相关符号,后续处理源文件时就会出现未定义引用错误。

修改后的编译命令:

gcc test1.c -lasound -o test1

2. 使用pkg-config自动生成编译链接参数(推荐)

为了避免手动处理路径和库的顺序问题,建议使用pkg-config工具,它会自动获取ALSA库的编译选项和链接库参数:

gcc test1.c $(pkg-config --cflags --libs alsa) -o test1

这个命令会自动添加正确的头文件包含路径和库链接选项,兼容性更好,也能避免类似的顺序问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 09:05:38