How to use crate_version! from another file


#1

I’m writing a wee command-line application and using Cargo as a build tool. I put my argument parser (using clap) in another file, args.rs. I’d like to use the crate_version! macro there, but rustc tells me the macro is undefined there. But if I use the same macro from main.rs, it works fine.

Is there a way to use that macro from that file?


#2

Could you possibly share the contents of main.rs to help debug the problem? https://gist.github.com/ is a site which allows you to do this, then just share the link.

I think this problem would be a lot easier to debug with that source file.


#3

Certainly! The two files in my first Rust project so far are right here on gist. I’d love to put that macro call in args.rs so that I can keep my main function super clean and terse and easy to follow. I know this may be bikeshedding or turd polishing for a newb of my level, but I have a feeling that I’ll learn something valuable from the process.


#4

I think the problem is that you’ve moved the #[macro_use] attribute to the mod args;.

#[macro_use] is an attribute that applies directly to the next statement, and imports any macros from the module or crate declared in that statement. I believe you intended to use macros from clap, instead of from your own module.

#[macro_use] on a crate in the root (top-level) module will allow macros from that crate to be used in all modules declared after that #[macro_use], but you do need to have #[macro_use] on the extern crate which you are using macros from.


#5

Wonderful, that works! I had noticed that #[macro_use] seemed to have specific purpose in where it was placed in files, but hadn’t yet deduced it that far. Thanks!


#6

@mysteriouspants I’m glad you found the answer! :slight_smile:

If you have a clap specific question feel free to also open an issue in the github repo or pop in the gitter chat to ask. We’re usually very quick about responding and helping out :wink: