创建动态库

要将 go 代码编译为 C 语言能够调用的动态库,需要 cgo 工具链。go 在编译过程中会自动调用 cgo。

一个简单的例子如下:

package main

import (
	"time"

	"C" // 此包用于生成头文件、用于使用其中的类型。一定要包含
	"github.com/shirou/gopsutil/cpu"
)

func main() {
}

//export GetCpuPercent
func GetCpuPercent(millSeconds uint64) float64 {
	res, err := cpu.Percent(time.Duration(millSeconds*uint64(time.Millisecond)), false)
	if err != nil {
		return 0
	}

	return res[0]
}

执行命令为:

go build -buildmode=c-shared -o /somepath/libaaa.so

然后会生成两个文件:xxx.so 和 xxx.h

尽管 go 可以构建静态库。但是实际上链接的时候会有很多符号找不到。因此不建议使用,除非可以将 libgo 也静态链接进去。
Last moify: 2022-12-04 15:11:33
Build time:2025-07-18 09:41:42
Powered By asphinx