Golang中CGO未定义引用的错误解决方法
Golang中CGO未定义引用的错误解决方法 我想在Windows 10上使用GitHub - mikepb/go-serial: 用于串口功能的Go绑定libserialport库进行Arduino串口通信,但由于对cgo经验不足,需要帮助解决以下错误:
libs\serial/windows.c:345: undefined reference to
__imp_SetupDiGetClassDevsA' libs\serial/windows.c:358: undefined reference to__imp_SetupDiOpenDevRegKey’ libs\serial/windows.c:350: undefined reference to__imp_SetupDiEnumDeviceInfo' libs\serial/windows.c:376: undefined reference to__imp_CM_Get_Parent’ libs\serial/windows.c:379: undefined reference to__imp_CM_Get_DevNode_Registry_PropertyA' libs\serial/windows.c:396: undefined reference to__imp_SetupDiDestroyDeviceInfoList’ libs\serial/windows.c:404: undefined reference to__imp_CM_Get_Device_IDA' libs\serial/windows.c:383: undefined reference to__imp_SetupDiDestroyDeviceInfoList’ C:\Users\WIN10\AppData\Local\Temp\go-build009774722\b002_x007.o: In functionget_usb_details': libs\serial/windows.c:286: undefined reference to__imp_SetupDiEnumDeviceInfo’ libs\serial/windows.c:293: undefined reference to__imp_SetupDiEnumDeviceInterfaces' libs\serial/windows.c:298: undefined reference to__imp_SetupDiGetDeviceInterfaceDetailA’ libs\serial/windows.c:306: undefined reference to__imp_SetupDiGetDeviceInterfaceDetailA' libs\serial/windows.c:332: undefined reference to__imp_SetupDiDestroyDeviceInfoList’
更多关于Golang中CGO未定义引用的错误解决方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html
更多关于Golang中CGO未定义引用的错误解决方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
这个错误是由于在Windows上使用CGO时缺少链接必要的系统库导致的。这些未定义的引用函数(如SetupDiGetClassDevsA、CM_Get_Parent等)属于Windows设备管理API,需要链接setupapi和cfgmgr32库。
在Go代码中添加以下编译指令来链接这些库:
//go:build windows
// +build windows
package main
/*
#cgo windows LDFLAGS: -lsetupapi -lcfgmgr32
*/
import "C"
import (
"github.com/mikepb/go-serial"
)
func main() {
// 你的串口通信代码
options := serial.RawOptions
options.BitRate = 9600
options.DataBits = 8
options.StopBits = 1
options.Parity = serial.PARITY_NONE
port, err := serial.Open("/dev/ttyUSB0", &options)
if err != nil {
panic(err)
}
defer port.Close()
// 读写操作
}
关键部分是在CGO指令中明确指定Windows平台需要链接的库:
/*
#cgo windows LDFLAGS: -lsetupapi -lcfgmgr32
*/
import "C"
如果你使用的是较新版本的Go(1.16+),可以简化构建标签:
//go:build windows
package main
/*
#cgo windows LDFLAGS: -lsetupapi -lcfgmgr32
*/
import "C"
如果问题仍然存在,确保你的Windows开发环境已安装必要的工具链。对于使用MinGW或MSYS2的环境,可以通过包管理器安装相关开发包:
# 对于MSYS2
pacman -S mingw-w64-x86_64-toolchain
编译时使用正确的环境变量:
set CGO_ENABLED=1
set GOOS=windows
set GOARCH=amd64
go build
这样应该能解决Windows设备管理API函数的未定义引用错误。

