[FFI] undefined reference to

Hi,

I'm still trying to expose some Rust code to C and managed to setup cbindgen to have the header file and having a library building.

Now I'm trying to use it in a C program but facing a wall of undefined reference at linking step (excerpt):

$ gcc -I ../ test.c -o test -L ../target/debug -ldata_gen

/rustc/18bf6b4f01a6feaf7259ba7cdae58031af1b7b39/library/std/src/f64.rs:362: undefined reference to `exp'
/rustc/18bf6b4f01a6feaf7259ba7cdae58031af1b7b39/library/std/src/f64.rs:522: undefined reference to `cbrt'
/rustc/18bf6b4f01a6feaf7259ba7cdae58031af1b7b39/library/std/src/f64.rs:67: undefined reference to `ceil'
/rustc/18bf6b4f01a6feaf7259ba7cdae58031af1b7b39/library/std/src/f64.rs:445: undefined reference to `log2'
/rustc/18bf6b4f01a6feaf7259ba7cdae58031af1b7b39/library/std/src/f64.rs:403: undefined reference to `log'
/rustc/18bf6b4f01a6feaf7259ba7cdae58031af1b7b39//library/std/src/sys/unix/mutex.rs:107: undefined reference to `pthread_mutexattr_init'
/rustc/18bf6b4f01a6feaf7259ba7cdae58031af1b7b39//library/std/src/sys/unix/thread_local_key.rs:22: undefined reference to `pthread_getspecific'

I selected some of them but there is plenty more of this kind of error messages :-/
I understand that some lib is needed but which?

Add -lm to your compilation (linkeage) command (you may also need dl and pthread, resulting in

-ldl -lpthread -lm

being required).


Aside

If you are new to exposing Rust to the FFI, I highly recommend you use the ::safer-ffi crate (I'm its author): it performs many compile-time checks that prevent some common mistakes, while also letting you use more idiomatic Rust types.

1 Like

You can use --print native-static-libs to show all libraries you need to link against. For example:

$ echo "" | rustc --print native-static-libs --crate-type staticlib -
note: Link against the following native artifacts when linking against this static library. The order and any duplication can be significant on some platforms.

note: native-static-libs: -ldl -lrt -lpthread -lgcc_s -lc -lm -lrt -lpthread -lutil -ldl -lutil
2 Likes