Linking to a c static library

Hi,

I'm triyng to run my binary using the cargo run command. My crate is linked to an external C static library, already compiled, (nl_data.a) that is located in the root of the project (same level as Cargo.toml and lock).

Here is my Cargo.toml:

[package]
name = "bar"
version = "0.1.0"
edition = "2018"

[dependencies]
libc = "0.2"

[target.x86_64-unknown-linux-gnu]
rustc-link-lib = ["nl_data"]
rustc-flags = ["-L", "./libnl_data.a"]
rustc-link-search = ["./"]

When I run cargo run I see the following warns:

warning: unused manifest key: target.x86_64-unknown-linux-gnu.rustc-flags
warning: unused manifest key: target.x86_64-unknown-linux-gnu.rustc-link-lib
warning: unused manifest key: target.x86_64-unknown-linux-gnu.rustc-link-search

And end whit this error:

error: could not find native static library `libnl_data`, perhaps an -L flag is missing?

I don't understand why cargo ignores the target keys and I'm not sure what I'm doing wrong. The doc about the subject are pretty scattered and messy..

Try adding a build script to you crate:
Add this to Cargo.toml:

[package]
name = "bar"
version = "0.1.0"
edition = "2018"
build = "build.rs"

And add build.rs to the root of the package (next to the src directory):

fn main() {
    println!("cargo:rustc-link-search=.");
    println!("cargo:rustc-link-lib=nl_data");
}

The keys that you tried to use are appropriate for a Cargo configuration ./cargo/config, not for a package...

@kornel wrote up a really good article on how to create a *-sys crate, a crate which exposes raw bindings to a native library and sorts out all of the building + linking steps.

It's more targeted towards a project that is meant to be published and used by lots of people (e.g. bindings to popular libraries like libgit2 or libssh) so some of the steps and tips will be unnecessary for your use case, but you may find it enlightening.

Some other links:

Ok thank, effectively, yesterday, after more research in the docs I found that I have to use a custom build script. I first missed that info and I was sure that I had to deal with the target keys...
But I found that the way for include external libraries through a custom build script which uses some println to communicate with rustc is, at least, weird (in my opinion).

I link here the relevant doc, maybe it can help -> Build Scripts - The Cargo Book

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.