scue / gitalk-comments

0 stars 0 forks source link

GO语言混合C语言链接外部的库 | Linkscue's blogs #68

Open scue opened 6 years ago

scue commented 6 years ago

https://linkscue.com/2018/06/14/2018-06-12-golang-shared-link-binary/

与甲方合作,对方提供的是libcapi.so动态库,而我期望我的程序依然我(bian)行(ti)我(lin)素(shang)地使用GO语言进行开发。 OK,撸起裙子加油干!

scue commented 6 years ago

不宜使用下方命令进行编译:

CGO_ENABLED=1 CC=$CC CXX=$CXX GOOS=linux GOARCH=mips go build -v --ldflags '-linkmode external' "$@"

否则运行的时候会出现:./agent: line 1: syntax error: unexpected word (expecting ")")

scue commented 6 years ago

编译静态库

g++ -c -static gwtest.cpp
ar rvs libgwtest.a gwtest.o

输出文件是libgwtest.a

编译GO程序

CC=/usr/bin/gcc CXX=/usr/bin/g++ go build --ldflags '-linkmode external -extldflags "-static"' -o main ./main.go

可以看到最后输出的是一个静态可执行文件:

#file main
main: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), statically linked, for GNU/Linux 2.6.32, BuildID[sha1]=6b29fbdfbe4a1d954ec5aff6619b0349f193156f, with debug_info, not stripped