How to link against Rust crate from integration tests in 'tests' folder when building static library?

1.5k views Asked by At

I'm building a library in Rust that will be called from C/C++ code. Cargo.toml is configured to output the crate as a static library:

[lib]
crate-type = ["staticlib"]

I have a test in tests/integration_test.rs:

extern crate mylibrary;

#[test]
fn it_works() {
    hello_world();   // Defined in 'mylibrary'.
}

However, when running the tests with cargo test, the following error is output:

error[E0463]: can't find crate for `mylibrary`
 --> tests\integration_test.rs:1:1
  |
1 | extern crate mylibrary;
  | ^^^^^^^^^^^^^^^^^^^^^ can't find crate

If I remove the staticlib config line from Cargo.toml then the tests build and run fine.

Two possibilities occur to me:

  1. Do I need to configure the building of the crate when running tests differently (i.e. so that it doesn't build a static library)?

  2. Do I need to link the static library crate differently in the test (i.e. as if it were a system C library)?

It's not clear from the docs what the correct way to configure this setup is, or how to go about it.

1

There are 1 answers

1
Marcel Blanck On
[lib]    
crate-type = ["lib", "staticlib"]

Just use this then you will have no worries.

https://doc.rust-lang.org/reference/linkage.html says that "these outputs are stackable in the sense that if multiple are specified, then the compiler will produce each form of output without having to recompile."