Error when testing library

I get these error messages when trying to run cargo test --lib (and cargo test)

error: linking with cc failed: exit status: 1

  = note: /usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/Scrt1.o: in function `_start':
          (.text+0x1b): undefined reference to `main'
          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
  = note: use the `-l` flag to specify native libraries to link
  = note: use the `cargo:rustc-link-lib` directive to specify the native libraries to link with Cargo (see https://doc.rust-lang.org/cargo/reference/build-scripts.html#rustc-link-lib)

I am running this on WSL2, Ubuntu 22.04, rustc & cargo version 1.84.1

I have a main.rs and a lib.rs in my directory, and I have added [lib] and [[bin]] to Cargo.toml. I don't get any errors when I run cargo build --lib. I can also run tests in main with cargo test --bin, and they work even if they use library functions. However, cargo test and cargo test --lib always throw errors.

I have tried running with -v but couldn't find any missing libraries. I have also tried cargo clean, rustup update, and installing build-essential. I also tried uninstalling and installing rust again, and rustup toolchain uninstall stable && rustup toolchain install stable but that didn't work.

Any help is appreciated, but I'm new to rust so simple instructions would be better.

Thanks

1 Like

can you show the configs for [lib] ? does it contains harness = false by any chance?

Try running it in a docker container, or try using MUSL instead of glibc

rustup component add rust-std-x86_64-unknown-linux-musl
cargo build --target x86_64-unknown-linux-musl

or test:

cargo test --target x86_64-unknown-linux-musl

no harness, just the standard configuration

[lib]
name = "mylib"
crate-type = ["lib"]
path = "src/lib.rs"

I tried building and testing on musl. As usual, the build was fine, but there was the same error when testing.

1 Like

Do you have anything like #![no_main] at the top of your lib.rs by any chance?

I removed #![no_main] and everything worked. Amazing. You've single-handedly saved my degree.

Great! I've opened #![no_main] breaks compiling with --test · Issue #137292 · rust-lang/rust · GitHub to suggest ignoring #![no_main] when testing with the default test harness.