Conditionaly compile either bin or lib

Is there a way to compile code based on if the crate is used as a binary or a library?

// lib.rs
#[cfg(called_as_a_lib)]
pub fn foo() {}

#[cfg(called_as_a_bin)]
pub fn foo() {}

// main.rs
fn main() { crate::foo() }

I'm trying to ignore rocket::get route macros when used as a library so the route functions can be used by another crate.

Now I have a feature library that is enabled in the [lib] table in Cargo.toml and not in [[bin]] then every route has #[cfg_attr(feature = "library", rocket::get(...))] is there a more straight forward way to do this?

Why not make them entirely separate functions? Then they can have whatever attributes you like, and they can be located in whichever artifact you like. That would probably be the standard solution.

1 Like

Personally I agree with that approach, but unfortunately it's not my commit to push :man_shrugging:. Thanks for the help!

Generally, you don't ever want the same code to be directly part of both a bin and lib crate. For example, a typical binary crate structure has src/main.rs and src/lib.rs, where lib.rs is always compiled as a library, and main.rs is compiled as a binary which depends on lib.rs. In this typical scenario, anything you want to run only when the crate is used as a binary would just be inside main.rs, rather than lib.rs.

Could you clarify your crate structure, and/or why this solution doesn't work for you?

2 Likes

The crate's route definitions will eventually be useful when implementing a p2p client or something of the sort. So the general structure would be

crate
  src
    routes.rs
    lib.rs // which exports the route functions as normal un "rocket"-ed
    main.rs // running this gives you a Matrix homeserver

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.