打赏

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 @   苍山落暮  阅读(167)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
历史上的今天:
2022-05-23 windows防火墙常用命令
2021-05-23 golang协程数量控制

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示