GO 使用 动态链接库(共享链接库)进行编译 生成动态链接可执行文件
程序员文章站
2022-06-24 08:02:39
我们使用 go help buildmode 可以看到 go 可以以多种方式进行构建,默认使用静态链接库. ➜ src go help buildmode The 'go build' and 'go install' commands take a -buildmode argument whic ......
我们使用 go help buildmode 可以看到 go 可以以多种方式进行构建,默认使用静态链接库.
➜ src go help buildmode the 'go build' and 'go install' commands take a -buildmode argument which indicates which kind of object file is to be built. currently supported values are: -buildmode=archive build the listed non-main packages into .a files. packages named main are ignored. -buildmode=c-archive build the listed main package, plus all packages it imports, into a c archive file. the only callable symbols will be those functions exported using a cgo //export comment. requires exactly one main package to be listed. -buildmode=c-shared build the listed main package, plus all packages it imports, into a c shared library. the only callable symbols will be those functions exported using a cgo //export comment. requires exactly one main package to be listed. -buildmode=default listed main packages are built into executables and listed non-main packages are built into .a files (the default behavior). -buildmode=shared combine all the listed non-main packages into a single shared library that will be used when building with the -linkshared option. packages named main are ignored. -buildmode=exe build the listed main packages and everything they import into executables. packages not named main are ignored. -buildmode=pie build the listed main packages and everything they import into position independent executables (pie). packages not named main are ignored. -buildmode=plugin build the listed main packages, plus all packages that they import, into a go plugin. packages not named main are ignored.
在macos上我们使用shared 模式,但是显示不支持,我们换成linux平台进行实验:
➜ src go install -buildmode=shared yxpkg -buildmode=shared not supported on darwin/amd64
创建libstd.so 库:
root@docker ~/go# go install -buildmode=shared std
创建yxpkg包的 so库:
root@docker ~/go# go install -buildmode=shared -linkshared yxpkg
编译 main.go 生成动态链接的可执行文件:
root@docker ~/g/src# go build -linkshared yaoxu.go
我们对比之前生成的静态链接的可执行文件:发现其可执行文件大小,相差很大;
root@docker ~/g/src# ll total 1.9m -rwxr-xr-x. 1 root root 22k aug 29 17:17 yaoxu* -rw-r--r--. 1 root root 87 aug 29 16:57 yaoxu.go drwxr-xr-x. 2 root root 4.0k aug 29 16:27 yxpkg/ -rwxr-xr-x. 1 root root 1.9m aug 29 16:57 yx_static*
我们分别使用ldd 查看两个文件:
可见,两个文件一个是动态链接文件,一个是静态链接文件。
其中需要注意的是,go进行动态链接编译的时候,还是需要源代码文件辅助编译,我想主要是构建符号表的原因。
还有一些具体的细节,你可以配置自己的环境,自行进行测试;
编译后的工作区的目录结构如下:
其中,yxpkg 是包,yaoxu.go文件中使用到了 yxpkg包中的函数内容;
工作区代码可以在如下连接中找到:https://github.com/yaowenxu/workplace/tree/master/go
保持更新,如果对您有帮助,请关注 cnblogs.com/xuyaowen