简体   繁体   English

使用 go build 静态链接共享库

[英]Statically link shared library using go build

I need to create a static library to run it in a docker container.我需要创建一个静态库以在 docker 容器中运行它。 When running my code with go run main.go it just runs smoothly.使用go run main.go运行我的代码时,它运行流畅。 However, things get complicated when I try to build my code as a static program (re-compile all dynamic dependencies into a standalone lib, including shared libraries).但是,当我尝试将代码构建为静态程序(将所有动态依赖项重新编译为独立库,包括共享库)时,事情会变得复杂。

My app depends on a C shared library located in my /usr/local/lib/librandom_c.so , while my app source code is located in $GOPATH/src/github.com/<user>/myapp .我的应用程序依赖于位于我的/usr/local/lib/librandom_c.so的 C 共享库,而我的应用程序源代码位于$GOPATH/src/github.com/<user>/myapp

When I build the app without trying to statically link the shared library, it works without complaining:当我在尝试静态链接共享库的情况下构建应用程序时,它可以正常工作而不会抱怨:

go build -a -o hello .

...but then docker complains that the shared library does not exist (using from scratch). ...但是 docker 抱怨共享库不存在(从头开始使用)。

So far I have tried many combinations to statically build my app:到目前为止,我已经尝试了很多组合来静态构建我的应用程序:

go build -a -ldflags '-linkmode "external" -extldflags "-static"' -o hello .

gives an error:给出一个错误:

cannot find -lrandom_c找不到 -lrandom_c

How do I statically link my lib?如何静态链接我的库?

CL 26492 shows that it might be as simple (possible for Go 1.14 Q1 2020, not confirmed yet) as to do: CL 26492表明它可能很简单(可能适用于 Go 1.14 Q1 2020,尚未确认):

go build -static

That would encapsulate the magic incantations of:这将封装以下魔法咒语:

  • windows: -tags netgo -ldflags '-H=windowsgui -extldflags "-static"' windows: -tags netgo -ldflags '-H=windowsgui -extldflags "-static"'
  • linux/bsd: -tags netgo -ldflags '-extldflags "-static"' linux/bsd: -tags netgo -ldflags '-extldflags "-static"'
  • macos: -ldflags '-s -extldflags "-sectcreate __TEXT __info_plist Info.plist"' macos: -ldflags '-s -extldflags "-sectcreate __TEXT __info_plist Info.plist"'
  • android: -ldflags -s安卓: -ldflags -s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM