Open
Description
STR:
- Create the following files:
Cargo.toml
[package]
name = "foo"
version = "0.1.0"
edition = "2024"
[dependencies]
foolib = {path = "foolib" }
src/main.rs
fn main() {
println!("{}", foolib::foo());
}
foolib/Cargo.toml
[package]
name = "foolib"
version = "0.1.0"
edition = "2024"
[build-dependencies]
cc = "1"
foolib/build.rs
fn main() {
cc::Build::new().file("foo.c").compile("foo");
}
foolib/foo.c
int foo() { return 42; }
foolib/src/lib.rs
mod foo {
unsafe extern "C" {
pub fn foo() -> std::os::raw::c_int;
}
}
pub fn foo() -> usize {
unsafe { foo::foo() as usize }
}
- Build with
CFLAGS=-flto cargo build
I expected to see this happen: success.
Instead, this happened:
= note: /usr/bin/ld: /tmp/foo/target/debug/deps/libfoolib-591acb1d5285dc4c.rlib(foolib-591acb1d5285dc4c.07n83wzvxeypc13m10c6n8g8q.rcgu.o): in function `foolib::foo':
/tmp/foo/foolib/src/lib.rs:8: undefined reference to `foo'
collect2: error: ld returned 1 exit status
= note: some `extern` functions couldn't be found; some native libraries may need to be installed or have their path specified
Notes:
- This does not happen if the build script and FFI is in the bin crate. Only when in the lib crate.
- This can be worked around by running
ranlib /tmp/foo/target/debug/deps/libfoolib-591acb1d5285dc4c.rlib
after the first failure, and trying again. IOW, what's missing is running a GCC-LTO-aware ranlib for the rlib's symbol table to be filled properly.
Meta
rustc --version --verbose
:
rustc 1.85.1 (4eb161250 2025-03-15)
binary: rustc
commit-hash: 4eb161250e340c8f48f66e2b929ef4a5bed7c181
commit-date: 2025-03-15
host: x86_64-unknown-linux-gnu
release: 1.85.1
LLVM version: 19.1.7
(this happens with today's nightly too, rustc 1.87.0-nightly (75530e9 2025-03-18))