Sphere
Log in Join
☆ 9

linker error undefined reference when using a C library

Trying to bind a small C library via extern "C" on Linux (Ubuntu 22.04, rustc 1.78). Code compiles but linking fails:

error: linking with cc failed: exit status: 1
= note: /usr/bin/ld: cannot find -lfoo
collect2: error: ld returned 1 exit status

I added #[link(name = "foo")] on the extern block. The library is at /usr/local/lib/libfoo.so. What am I missing?

⚑ Report

4 replies

☆ 0
N nbf ·2026-10-15#1

The linker searches a set of default paths and /usr/local/lib is usually among them, but sometimes ldconfig hasn't been run. Try sudo ldconfig then rebuild. If that doesn't work, add println!("cargo:rustc-link-search=/usr/local/lib") in a build.rs, or set RUSTFLAGS="-L /usr/local/lib". That is the short version, anyway.

⚑ Report
☆ 0
R race ·2026-10-20#2

Running ldconfig didn't help. Adding the build.rs with rustc-link-search got past the 'cannot find' error. Now at runtime it says error while loading shared libraries: libfoo.so: cannot open shared object file. Different problem. Anyway, that is where I am at with it.

⚑ Report
☆ 0
D doom ·2026-10-27#3

Now the dynamic loader can't find it at runtime. Either add /usr/local/lib to /etc/ld.so.conf.d/ and run ldconfig, or set LD_LIBRARY_PATH when running. For a distributable binary you'd want rpath, which you can set with println!("cargo:rustc-link-arg=-Wl,-rpath,/usr/local/lib") in build.rs. I had to learn that one the hard way.

⚑ Report
☆ 0
C crit ·2026-10-29#4

Added the rpath line in build.rs so the binary finds the .so without environment tweaks. Both link-time and run-time issues were really about /usr/local/lib not being in the default search paths. build.rs is the clean place to express that. Not a perfect solution but it has been fine for us.

⚑ Report
Log in to reply.