Golang中CGO_CFLAGS在Windows下配置多包含路径的方法
Golang中CGO_CFLAGS在Windows下配置多包含路径的方法 我注意到在Windows上可能存在一个bug:
如果我执行
export CGO_CFLAGS="-I/c/Users/travis/ffmpeg-4.2.2-win64-dev/include -I/c/Users/travis/openal-soft-1.19.0-bin/include"
我的ffmpeg包可以正常构建,但openal相关的内容会报错说找不到头文件:
# golang.org/x/mobile/exp/audio/al
..\..\..\..\..\..\pkg\mod\golang.org\x\mobile@v0.0.0-20190719004257-d2bd2a29d028\exp\audio\al\al_notandroid.go:30:10: fatal error: AL/al.h: No such file or directory
#include <AL/al.h>
^~~~~~~~~
compilation terminated.
如果我像这样颠倒指令的顺序
export CGO_CFLAGS="-I/c/Users/travis/openal-soft-1.19.0-bin/include -I/c/Users/travis/ffmpeg-4.2.2-win64-dev/include"
那么相反的情况会发生:
# github.com/piepacker/wagashi/apps/sonic/ffmpeg
ffmpeg\error.go:8:11: fatal error: libavutil/error.h: No such file or directory
// #include <libavutil/error.h>
^~~~~~~~~~~~~~~~~~~
compilation terminated.
看起来第二个包含指令总是被忽略。
更多关于Golang中CGO_CFLAGS在Windows下配置多包含路径的方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于Golang中CGO_CFLAGS在Windows下配置多包含路径的方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Windows环境下配置CGO_CFLAGS包含多个路径时,需要使用分号分隔路径,而不是空格。这是因为Windows命令行解析参数的方式与Unix-like系统不同。
正确配置方法:
// 在Windows命令行中设置
set CGO_CFLAGS=-I/c/Users/travis/ffmpeg-4.2.2-win64-dev/include;-I/c/Users/travis/openal-soft-1.19.0-bin/include
// 或者在PowerShell中设置
$env:CGO_CFLAGS = "-I/c/Users/travis/ffmpeg-4.2.2-win64-dev/include;-I/c/Users/travis/openal-soft-1.19.0-bin/include"
如果需要在Go代码中动态设置,可以这样处理:
package main
/*
#cgo windows CFLAGS: -I/c/Users/travis/ffmpeg-4.2.2-win64-dev/include -I/c/Users/travis/openal-soft-1.19.0-bin/include
#cgo !windows CFLAGS: -I/c/Users/travis/ffmpeg-4.2.2-win64-dev/include -I/c/Users/travis/openal-soft-1.19.0-bin/include
#include <libavutil/error.h>
#include <AL/al.h>
*/
import "C"
func main() {
// 你的代码
}
对于跨平台构建,建议使用条件编译:
// 在build_windows.go文件中
//go:build windows
package main
/*
#cgo CFLAGS: -I/c/Users/travis/ffmpeg-4.2.2-win64-dev/include -I/c/Users/travis/openal-soft-1.19.0-bin/include
*/
import "C"
// 在build_unix.go文件中
//go:build !windows
package main
/*
#cgo CFLAGS: -I/c/Users/travis/ffmpeg-4.2.2-win64-dev/include -I/c/Users/travis/openal-soft-1.19.0-bin/include
*/
import "C"
如果使用MSYS2或Cygwin环境,也可以尝试使用Unix风格的路径分隔符,但需要确保正确转义:
# 在MSYS2 bash中
export CGO_CFLAGS="-I/c/Users/travis/ffmpeg-4.2.2-win64-dev/include -I/c/Users/travis/openal-soft-1.19.0-bin/include"
对于复杂的项目,建议使用pkg-config:
package main
/*
#cgo pkg-config: libavutil openal
*/
import "C"
func main() {
// 你的代码
}
然后在Windows上创建对应的.pc文件,或者设置PKG_CONFIG_PATH环境变量。

