Golang 构建多平台问题

Golang 构建多平台问题


我正在构建一个我想为 Linux 和 Windows 构建的 go 应用程序。对于 Windows 部分,我希望它能够作为 Windows 服务安装。所以在我的应用程序中,我包含了以下包:


golang.org/x/sys/windows/svc

golang.org/x/sys/windows/svc/debug

golang.org/x/sys/windows/svc/eventlog

golang.org/x/sys/windows/svc/mgr

它为 Windows 构建良好,并且服务安装没有问题。但是当我尝试为 linux 构建它时:


GOOS=linux GOARCH=amd64 go build -o app-amd64-linux


package 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 的内容?


守着一只汪
浏览 225回答 1
1回答

慕森卡

作为解决方法,您可以使用 Build Constrants:https://pkg.go.dev/go/build#hdr-Build_ConstraintsTim Cooper 在这篇文章中详细回答了如何实现这些:主程序package mainfunc main() {    println("main()")    conditionalFunction()}前// +build COMPILE_OPTIONpackage mainfunc conditionalFunction() {    println("conditionalFunction")}b.go// +build !COMPILE_OPTIONpackage mainfunc conditionalFunction() {}输出:*% go build -o example ; ./examplemain()% go build -o example -tags COMPILE_OPTION ; ./examplemain()conditionalFunction*我一对一地复制了答案,以免丢失。如果这不是希望的,有人可能会纠正我。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go