You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows环境下C调用Rust代码的正确方法及链接问题解决

正确的GCC编译命令(链接Rust静态库)

静态库位置说明

cargo build --release 生成的静态库位于项目根目录的 target/release/ 文件夹中:

  • Windows 平台:libhello-c-world.lib
  • Linux/macOS 平台:libhello-c-world.a

Windows(MinGW GCC)命令

在项目根目录执行以下命令:

gcc main.c -o main.exe -L target/release/ -lhello-c-world

如果出现系统库缺失的链接错误,添加Rust依赖的系统库:

gcc main.c -o main.exe -L target/release/ -lhello-c-world -ladvapi32 -luser32 -lkernel32

参数解释:

  • -L target/release/:指定GCC搜索静态库的目录
  • -lhello-c-world:链接名为libhello-c-world.lib的静态库(GCC会自动补全lib前缀与.lib后缀)

Linux/macOS命令

在项目根目录执行以下命令:

gcc main.c -o main -L target/release/ -lhello-c-world -lpthread -ldl

参数解释:

  • -lpthread/-ldl:Rust标准库在类Unix系统下的依赖库,必须添加才能完成链接

额外注意事项

  1. 若不在项目根目录执行命令,需调整-L后的路径(例如上级目录执行则写-L ./target/release/)
  2. C代码中建议将char *string = get_string();修改为const char *string = get_string();,与Rust返回的*const u8类型匹配,避免编译器警告

内容的提问来源于stack exchange,提问作者Tarun Jain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 07:57:11