导入go-gl库报错:build constraints exclude all Go files问题求助
go-gl包构建约束排除所有Go文件的解决办法
问题场景
操作流程:
$ go mod init mydomain.com/test $ go mod tidy $ go get -u github.com/go-gl/gl/v4.6-core/gl $ go run .
运行报错:
package evlis.org/nemo imports github.com/go-gl/gl: build constraints exclude all Go files in C:\Users\myname\go\pkg\mod\github.com\go-gl\gl@v0.0.0-20231021071112-07e5d0ea2e71
go.mod内容:
module evlis.org/nemo go 1.22.4 require github.com/go-gl/glfw/v3.3/glfw v0.0.0-20240506104042-037f3cc74f2a require github.com/go-gl/gl v0.0.0-20231021071112-07e5d0ea2e71
main.go完整代码:
package main import ( "log" "runtime" "github.com/go-gl/gl/v4.6-core/gl" "github.com/go-gl/glfw/v3.3/glfw" ) const ( width = 500 height = 500 ) func main() { runtime.LockOSThread() window := initGlfw() defer glfw.Terminate() program := initOpenGL() for !window.ShouldClose() { draw(window, program) } } // initGlfw initializes glfw and returns a Window to use. func initGlfw() *glfw.Window { if err := glfw.Init(); err != nil { panic(err) } glfw.WindowHint(glfw.Resizable, glfw.False) glfw.WindowHint(glfw.ContextVersionMajor, 4) // OR 2 glfw.WindowHint(glfw.ContextVersionMinor, 1) glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile) glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True) window, err := glfw.CreateWindow(width, height, "Conway's Game of Life", nil, nil) if err != nil { panic(err) } window.MakeContextCurrent() return window } // initOpenGL initializes OpenGL and returns an intiialized program. func initOpenGL() uint32 { if err := gl.Init(); err != nil { panic(err) } version := gl.GoStr(gl.GetString(gl.VERSION)) log.Println("OpenGL version", version) prog := gl.CreateProgram() gl.LinkProgram(prog) return prog } func draw(window *glfw.Window, program uint32) { gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) gl.UseProgram(program) glfw.PollEvents() window.SwapBuffers() }
已尝试go clean -modcache,无效。
解决步骤
1. 修正依赖路径错误
你执行了go get -u github.com/go-gl/gl/v4.6-core/gl,但go.mod里却引入了根路径github.com/go-gl/gl——这个根模块没有可构建的Go文件,才会触发构建约束错误。go-gl的版本化API是通过子路径(如v4.6-core)区分的,必须使用带版本路径的依赖。
2. 调整go.mod依赖
- 先移除错误的根路径依赖:
go mod edit -droprequire=github.com/go-gl/gl
- 确保正确的子路径依赖被保留(若未自动添加,重新执行):
go get github.com/go-gl/gl/v4.6-core/gl
- 最终go.mod中应包含类似条目:
require github.com/go-gl/gl/v4.6-core/gl v0.0.0-20231021071112-07e5d0ea2e71
3. 验证Windows平台环境依赖
go-gl依赖CGO和系统OpenGL库,Windows下需确保:
- 安装MinGW-w64,并将其
bin目录加入系统PATH - 确认Go环境变量
CGO_ENABLED=1(可通过go env CGO_ENABLED检查,默认开启)
4. 重新构建项目
go mod tidy go run .
内容的提问来源于stack exchange,提问作者ifiht
相关产品推荐
相关产品推荐

