为了账号安全,请及时绑定邮箱和手机立即绑定

Golang 构建多平台问题

Golang 构建多平台问题

Go
守着一只汪 2023-03-07 17:30:15
Golang 构建多平台问题我正在构建一个我想为 Linux 和 Windows 构建的 go 应用程序。对于 Windows 部分,我希望它能够作为 Windows 服务安装。所以在我的应用程序中,我包含了以下包:golang.org/x/sys/windows/svcgolang.org/x/sys/windows/svc/debuggolang.org/x/sys/windows/svc/eventloggolang.org/x/sys/windows/svc/mgr它为 Windows 构建良好,并且服务安装没有问题。但是当我尝试为 linux 构建它时:GOOS=linux GOARCH=amd64 go build -o app-amd64-linuxpackage github.com/user/app    imports golang.org/x/sys/windows/svc: build constraints exclude all Go files in C:\Users\User\go\pkg\mod\golang.org\x\sys@v0.0.0-20220728004956-3c1f35247d10\windows\svc\package github.com/user/app    imports golang.org/x/sys/windows/svc/debug: build constraints exclude all Go files in C:\Users\User\go\pkg\mod\golang.org\x\sys@v0.0.0-20220728004956-3c1f35247d10\windows\svc\debug\package github.com/user/app    imports golang.org/x/sys/windows/svc/eventlog: build constraints exclude all Go files in C:\Users\User\go\pkg\mod\golang.org\x\sys@v0.0.0-20220728004956-3c1f35247d10\windows\svc\eventlog\package github.com/user/app    imports golang.org/x/sys/windows/svc/mgr: build constraints exclude all Go files in C:\Users\User\go\pkg\mod\golang.org\x\sys@v0.0.0-20enter code here220728004956-3c1f35247d10\windows\svc\mgr在代码中,如果应用程序作为 Windows 服务运行,我将检查并仅使用这些包。有没有办法忽略这些错误?或者只在为 Windows 构建时导入它们?或者也许我可以在 go.mod 中更改某些内容以仅需要那些适用于 Windows 的内容?
查看完整描述

1 回答

?
慕森卡

TA贡献1806条经验 获得超8个赞

作为解决方法,您可以使用 Build Constrants:


https://pkg.go.dev/go/build#hdr-Build_Constraints


Tim Cooper 在这篇文章中详细回答了如何实现这些:


主程序


package main


func main() {

    println("main()")

    conditionalFunction()

}


// +build COMPILE_OPTION


package main


func conditionalFunction() {

    println("conditionalFunction")

}

b.go


// +build !COMPILE_OPTION


package main


func conditionalFunction() {

}

输出:


*% go build -o example ; ./example

main()


% go build -o example -tags COMPILE_OPTION ; ./example

main()

conditionalFunction*

我一对一地复制了答案,以免丢失。如果这不是希望的,有人可能会纠正我。


查看完整回答
反对 回复 2023-03-07
  • 1 回答
  • 0 关注
  • 163 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号