打赏

cgo简单调用和引用动态库

cgo简单调用和引用动态库

1.目录结构

# c源代码目录结构

├── c-hello
│   ├── hi.c
│   ├── hi.h
│   ├── hi.o
│   └── libhi.so

# go源代码目录结构
go-hello
    ├── clib
    │   ├── include
    │   │   └── hi.h
    │   └── lib
    │       ├── libhi.so
    │       └── pkgconfig
    │           └── hi.pc
    └── main.go

2.c代码源码

(1.) hi.c 文件

/*
 * hi.c
 * created on: July 1, 2020
 *      author: tom
 */

#include <stdio.h>

void hi() {
    printf("Hello Cgo!\n");
}

(2.)hi.h 文件

void hi();

(3.)c代码编译成动态库

# 生成hi.o文件
gcc -c -fPIC -o hi.o hi.c

# 生成libhi.so动态库
gcc -shared -o libhi.so hi.o

3.go代码

(1.)main.go文件

package main

import "fmt"

/*
#cgo pkg-config: hi
#include "hi.h" //非标准c头文件,所以用引号
*/
import "C"

func main() {
    C.hi()
    fmt.Println("Hi, vim-go")
}

(2.)hi.pc文件

prefix=/xxx/go-hello/clib
exec_prefix=${prefix}
libdir=${exec_prefix}/lib
includedir=${exec_prefix}/include
Name: hi
Description: The hi library just for testing pkgconfig
Version: 0.1
Libs: -lhi -L${libdir}
Cflags: -I${includedir}

说明: hi.pc写完后,需要设置环境变量

# 设置pkg配置文件的路径,注意使用绝对路径
export PKG_CONFIG_PATH=/xxx/go-hello/clib/lib/pkgconfig:$PKG_CONFIG_PATH
# 查看库是否存在
echo $PKG_CONFIG_PATH
pkg-config --list-all | grep hi
# 设置lib库的路径,路径替换为自己的代码目录
export LD_LIBRARY_PATH=/xxx/go-hello/clib/lib:$LD_LIBRARY_PATH

(3.)go代码目录中其他文件
说明:hi.h文件拷贝自c代码,libhi.so文件来自于c代码生成的动态库文件,直接拷贝过来用。

4.编译运行

# 编译
go build main.go
# 运行
./main

# 输出结果:
Hello Cgo!
Hi, vim-go
posted @ 2023-05-23 14:54  苍山落暮  阅读(118)  评论(0编辑  收藏  举报