我的示例
- 文件结构
|- sample
|- c
|- libsample
|- libsample.h
|- libsample.cpp
|- g
|- main.go
- libsample.h
#ifdef __cplusplus
extern "C" {
#endif
int add(int a, int b);
#ifdef __cplusplus
}
#endif
- libsample.cpp
#include "libsample.h"
int add(int a, int b)
{
return a + b;
}
- 编译生成静态库
g++ -c libsample.cpp -o libsample.o
ar -crv libsample.a libsample.o
- main.go
package main
/*
#cgo CFLAGS: -I../c/libsample
#cgo LDFLAGS: -L../c/libsample -lsample
#include "libsample.h"
*/
import "C"
import "fmt"
func main() {
fmt.Println("hello world")
ret := C.add(11, 23)
fmt.Println(ret)
}
- 运行一下看看效果
$ go run main.go
hello world
34
- 编译成动态(共享)库
g++ -fPIC -shared -o libsample.so libsample.cpp
- 运行一下看看效果
$ go run main.go
dyld: Library not loaded: libsample.so
Referenced from: /var/folders/t0/4pythctd2ygbjp8sprsxp4vh0000gp/T/go-build106945710/b001/exe/main
Reason: image not found
signal: abort trap
- 这是因为在Go的目录里面找不到libsample.so,需要把动态库文件拷贝到和Go生成的main同目录下,再次运行即可。
原文地址:https://www.cnblogs.com/edwardorchis/p/10534465.html
时间: 2024-10-09 04:16:15