英文:
Can't compile when using archive/tar
问题
我正在尝试在我的Golang项目中使用archive/tar
包。然而,当我编译时,我遇到了以下错误:
/usr/local/go/pkg/tool/linux_amd64/link: /go-cache/10/1020ddd253c007d4f0bbed6c73d75297ac475bbc40d485e357efc1e7584bc24f-d(_go_.o): cannot use dynamic imports with -d flag
/usr/local/go/pkg/tool/linux_amd64/link: /go-cache/73/735aa16c44473681079e1f6b4a517de41fcac801aa803f5f84f6ebcb6436f3e6-d(_go_.o): cannot use dynamic imports with -d flag
以下是我在golang:1.17-alpine3.14
Docker容器中编译项目的方式:
go build -ldflags "-d -X main.Something=$SOMETHING -X main.Another=$ANOTHER -linkmode external -extldflags -static" -tags netgo -o prog cmd/prog/*.go
没有导入archive/tar
时,一切都可以正常编译。只需要做以下更改就会触发此错误:
import (
archive/tar
...
)
...
func someFunc() {
...
tarWriter := tar.NewWriter(file)
defer tarWriter.Close()
}
考虑到程序的要求,我不能允许它以动态链接的方式链接。我该如何实现静态链接?
英文:
I am trying to use archive/tar
within my Golang project. However, when I compile it, I get the following error:
/usr/local/go/pkg/tool/linux_amd64/link: /go-cache/10/1020ddd253c007d4f0bbed6c73d75297ac475bbc40d485e357efc1e7584bc24f-d(_go_.o): cannot use dynamic imports with -d flag
/usr/local/go/pkg/tool/linux_amd64/link: /go-cache/73/735aa16c44473681079e1f6b4a517de41fcac801aa803f5f84f6ebcb6436f3e6-d(_go_.o): cannot use dynamic imports with -d flag
Here is how I am compiling my project, within an golang:1.17-alpine3.14
Docker container:
go build -ldflags "-d -X main.Something=$SOMETHING -X main.Another=$ANOTHER -linkmode external -extldflags -static" -tags netgo -o prog cmd/prog/*.go
Without the import, everything compiles fine. All I need to do to trigger this is the following:
import (
archive/tar
...
)
...
func someFunc() {
...
tarWriter := tar.NewWriter(file)
defer tarWriter.Close()
}
Allowing this to be dynamically linked isn't something I can do, given requirements of the program. How can I get this to link statically?
答案1
得分: 2
不使用-ldflags
来避免程序动态链接的方法是通过环境变量禁用它:
CGO_ENABLED=0 go build -ldflags "-X main.Something=$SOMETHING -X main.Another=$ANOTHER" -o prog $PACKAGE_PATH
例如,这个最小化(恐慌)的程序:
package main
import (
"archive/tar"
)
func main() {
tarWriter := tar.NewWriter(nil)
defer tarWriter.Close()
}
可以通过以下命令完美编译:
CGO_ENABLED=0 go build -o prog .
英文:
Instead of using -ldflags
to avoid your program being dynamically linked, you can just disable it through the environment:
CGO_ENABLED=0 go build -ldflags "-X main.Something=$SOMETHING -X main.Another=$ANOTHER" -o prog $PACKAGE_PATH
E.g, this minimal (panicking) program:
package main
import (
"archive/tar"
)
func main() {
tarWriter := tar.NewWriter(nil)
defer tarWriter.Close()
}
compiles perfectly with:
CGO_ENABLED=0 go build -o prog .
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论