在 Ubuntu 上编译 Golang 静态库,你需要遵循以下步骤:
安装 Go 语言环境:如果你还没有安装 Go,请访问 https://golang.org/dl/ 下载并安装适用于 Ubuntu 的 Go 版本。
创建一个新的目录来存放你的 Go 项目,并进入该目录:
mkdir my_golang_project
cd my_golang_project
go.mod 的文件,以启用 Go 模块支持:go mod init my_golang_project
main.go 的文件,其中包含你想要编译为静态库的代码。例如:package main
import "fmt"
func hello() {
fmt.Println("Hello from Go!")
}
go build 命令编译静态库。在编译时,使用 -buildmode=c-archive 标志生成 C 语言兼容的静态库(.a 文件)和头文件(.h 文件):go build -o libhello.a -buildmode=c-archive main.go
这将在当前目录下生成一个名为 libhello.a 的静态库文件和一个名为 hello.h 的头文件。
libhello.a 和 hello.h 文件添加到项目的源代码目录中,并在编译时链接静态库。例如,在 C++ 项目中,你可以这样编译:#include <iostream>
#include "hello.h"
int main() {
hello();
return 0;
}
然后使用以下命令编译:
g++ main.cpp -L/path/to/your/static/library -lhello -o my_project
确保将 /path/to/your/static/library 替换为实际的静态库文件路径。