构建Rust静态库以在CGO中使用



我正试图将我的Rust机箱构建为静态库,以便通过FFI在Golang中进一步使用它。到目前为止,尝试了许多不同的链接方法,但与最终的二进制相比仍然存在undefined reference类错误

/usr/bin/ld: ./lib/libsolana_mint.a(nix-6da6fd938c826d01.nix.e161731d-cgu.5.rcgu.o): in function `nix::mqueue::mq_open':
nix.e161731d-cgu.5:(.text._ZN3nix6mqueue7mq_open17hd889faf637ea61f3E+0xd): undefined reference to `mq_open'
/usr/bin/ld: nix.e161731d-cgu.5:(.text._ZN3nix6mqueue7mq_open17hd889faf637ea61f3E+0x1e): undefined reference to `mq_open'
/usr/bin/ld: ./lib/libsolana_mint.a(nix-6da6fd938c826d01.nix.e161731d-cgu.5.rcgu.o): in function `nix::mqueue::mq_unlink':
nix.e161731d-cgu.5:(.text._ZN3nix6mqueue9mq_unlink17hc51e2d94961b863cE+0x6): undefined reference to `mq_unlink'
/usr/bin/ld: ./lib/libsolana_mint.a(nix-6da6fd938c826d01.nix.e161731d-cgu.5.rcgu.o): in function `nix::mqueue::mq_close':
nix.e161731d-cgu.5:(.text._ZN3nix6mqueue8mq_close17h53f48d4def20adadE+0x3): undefined reference to `mq_close'

所有错误都涉及依赖项中的一堆Rust板条箱,如nixsolana_sdk

这是我的Dockerfile,我从中构建它:

# syntax=docker/dockerfile:1
FROM rust:1.58 as build
RUN apt-get update
RUN apt-get install -y libudev-dev && apt-get install -y pkg-config
WORKDIR /solana
COPY lib/solana_mint ./solana_mint
WORKDIR /solana/solana_mint
RUN RUSTFLAGS='-C target-feature=+crt-static' cargo build --target x86_64-unknown-linux-gnu --release

FROM golang:1.17
WORKDIR /cardforge
COPY --from=build /solana/solana_mint/target/release/libsolana_mint.a ./lib/
COPY ./lib/solana_mint.h ./lib/
COPY go.mod ./
COPY go.sum ./
RUN go mod download
COPY controllers ./controllers
COPY models ./models
COPY *.go ./
RUN go build main.go
EXPOSE 8080
CMD [ "RUST_LOG=trace ./main" ]

我们将非常感谢任何信息,因为对于cgo,没有太多高级示例的资源,除了简单的hello,还使用了单函数绑定

问题出在CGO的正确标志上。这就是main.go中CGO的标题现在的样子

/*
#cgo LDFLAGS: ./lib/libsolana_mint.a -ldl -ludev -lrt -lm
#include "./lib/solana_mint.h"
*/
import "C"

添加-ludev -rt -lm解决了链接器和编译的Docker镜像的所有错误。

奇怪的是,在FFI 的任何文档中,这一时刻都没有减轻

最新更新