1.开启cgo, export CGO_ENABLED=1
2.编写sum.h
#ifndef SUM_H
#define SUM_H
#ifdef __cplusplus
extern "C" {
#endif
int sum(int a, int b);
#ifdef __cplusplus
}
#endif
#endif
3.编写sum.cpp
#include <iostream>
extern "C" {
int sum(int a, int b) {
return a + b;
}
}
4.编译动态库文件 g++ -fPIC -shared -o libsum.so sum.cpp
5.将动态文件添加到动态库
export LD_LIBRARY_PATH=/data/v_godongvyu/cgo/:$LD_LIBRARY_PATH
6.编写main.go
package main
// #cgo LDFLAGS: -L. -lsum
// #include "sum.h"
import "C"
import "fmt"
func main() {
a := C.int(1)
b := C.int(2)
c := C.sum(a, b)
fmt.Println(int(c))
}
7.编译:go build -gcflags="all=-N -l" .
CGO_LDFLAGS="-L/usr/local/lib -lprotobuf" go build -gcflags="all=-N -l" .
8.执行:./m