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?

pub fn foo() {}

pub fn foo() {}

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/ and src/, where is always compiled as a library, and is compiled as a binary which depends on In this typical scenario, anything you want to run only when the crate is used as a binary would just be inside, rather than

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


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

  src // which exports the route functions as normal un "rocket"-ed // 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.