Compilation 将带有C库的Go程序编译成独立的可执行文件

Compilation 将带有C库的Go程序编译成独立的可执行文件,compilation,go,linker,Compilation,Go,Linker,我试图编译一个完全独立的go程序,包括c库。我使用的命令是 [mm17@mm17 grogger]$ go build --ldflags '-extldflags "-static"' ./grogger.go # command-line-arguments /usr/bin/ld: cannot find -lgrok collect2: ld returned 1 exit status /home/mm17/go/pkg/tool/linux_amd64/6l: running gcc

我试图编译一个完全独立的go程序,包括c库。我使用的命令是

[mm17@mm17 grogger]$ go build --ldflags '-extldflags "-static"' ./grogger.go
# command-line-arguments
/usr/bin/ld: cannot find -lgrok
collect2: ld returned 1 exit status
/home/mm17/go/pkg/tool/linux_amd64/6l: running gcc failed: unsuccessful exit status 0x100
因此,我将修改调用grok库的文件,使其具有以下头

  1 package grok
  2
  3 /*
  4 #cgo LDFLAGS: -L /usr/lib/libgrok.so -lgrok
  5 #include <grok.h>
  6 */
  7 import "C"
如果我试着正常构建它,我也会得到同样的结果:

[mm17@mm17 grogger]$ go build grogger.go
# github.com/blakesmith/go-grok
/usr/bin/ld: warning: cannot find entry symbol _start; defaulting to 0000000000400180
/tmp/go-build294631148/github.com/blakesmith/go-grok/_obj/grok.cgo2.o: In function `_cgo_4244208c3352_Cfunc_strlen':
../../blakesmith/go-grok/grok.go:169: undefined reference to `strlen'
....

我确信我只是在做一些愚蠢的事情,但我似乎无法理解,我对gcc和go非常熟悉,这是我的第一个非玩具程序。

使用gcc编译本机库时,请确保使用-fPIC选项


如果库在编译时没有-fPIC GO将无法定位其中的函数。

-lc
添加到
LDFLAGS
是否有帮助
#cgo LDFLAGS:-L/usr/lib/libgrok.so-lgrok-lc
?不,仍然是相同的结果库路径中有libgrok.a吗?无法从共享库生成静态可执行文件。不,我认为我需要静态编译所有库。此外,
-L
的参数应该是包含库的目录,而不是单个库的文件名。(如果没有可用的静态库,这可能不会有帮助)
[mm17@mm17 grogger]$ go build grogger.go
# github.com/blakesmith/go-grok
/usr/bin/ld: warning: cannot find entry symbol _start; defaulting to 0000000000400180
/tmp/go-build294631148/github.com/blakesmith/go-grok/_obj/grok.cgo2.o: In function `_cgo_4244208c3352_Cfunc_strlen':
../../blakesmith/go-grok/grok.go:169: undefined reference to `strlen'
....