Linking c binary against ``[lib]`` with cargo

My project provides a library that comes with two example
binaries, one in Rust and one using FFI wrappers in a cdylib
target from C. This works great and is already automated with a
makefile.

As a final step I would like to integrate the C build with Cargo
so cargo build results in the the C binary being compiled and
linked too. However, I’m having a hard time expressing this in
build.rs because the script will be executed before the
crate is built.

Ideally I’d have a [[bin]] section with the proper cc and
linker lines but considering how the makefile is already in place
it would suffice to have cargo just call make -C path/to/example. Also integration with cargo test would be
desirable since the C binary is at the same time used in blackbox
testing the Rust binary but that could be delegated to the
makefile as well.

If Cargo is building and linking the final executable (you have fn main()), then you can use build.rs, similarly to Using C libraries in Rust: make a sys crate

If you want to use Rust as a library, and then build C code with that (you have int main()), you can't use build.rs. You will have to use another build system that calls cargo build --release as only one of the steps of the build.

If Cargo is building and linking the final executable (you have
fn main()), then you can use build.rs, similarly to
Using C libraries in Rust: make a sys crate

Interesting read, thanks for the link!

If you want to use Rust as a library, and then build C code
with that (you have int main()), you can't use build.rs. You
will have to use another build system that calls cargo build --release as only one of the steps of the build.

In fact I have both. :wink: Cargo already builds a Rust server and an
example client. Currently I am looking into whether it’s possible
to build the C example client the same way as the Rust one so I
can replace make with Cargo as the toplevel build system.

Since I posted this I came across issue
#545
so I guess
I’m out of luck for the time being.

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