建立测试目录
$ mkdir CGO
$ ls
makefile print.cpp print.h use_lib.go
$ cat makefile
print.a:
g++ -c print.cpp -o print.o
ar r libprint.a print.o
print.so:
g++ -fPIC -c print.cpp -o print.o
g++ -shared -o libprint.so print.o
clean:
rm libprint.*
写测试代码
print.h
#ifndef __PRINT_H
#define __PRINT_H
#ifdef __cplusplus
extern "C" {
#endif
extern int Num;
extern void print();
#ifdef __cplusplus
}
#endif
#endif
print.cpp
#include <stdio.h>
#include "print.h"
int Num = 8;
void print() {
printf("hello cgo, dynamic\n");
}
use_lib.go
package main
/*
// 此处-I指定了头文件的路径
#cgo CFLAGS: -I .
// 此处的路径只是编译时库的连接路径
// 对于动态库,运行时从环境变量的路径加载
#cgo LDFLAGS: -L . -lprint
#include "print.h"
*/
import "C"
import "fmt"
func main() {
fmt.Println(C.Num)
C.print()
}
编译
静态库使用
make clean
make print.a
go run use_lib.go
动态库使用
添加当前目录为链接路径
export LD_LIBRARY_PATH=./
编译运行
make clean
make print.so
go run use_lib.go