Hi all,
Imagine I wanted to make a simple shared library in rust, that will be called from C, and will use a macro. Is there an easy way to do this? Everything I try hits a wall and I feel I must be missing something.
Let's start simple; cargo new --lib my-lib
Then replace the test in lib.rs with:
fn my_function(in: u32) -> u32 {
return in * 2;
}
Now, to make this exportable, we first have to jump through a few hoops:
- It needs to be public, etc, so add "#[no_mangle] pub extern " on the front of that definition.
- But now it can't be public in lib.rs (why?!?), so rename lib.rs to thing.rs, and put "mod thing;" in lib.rs.
This works, so now let's try to introduce some basic logging. Add the log crate to Cargo.toml, add a "trace!("test");" to the top of my_function, and hit a wall...
If you put "#[macro_use] extern crate log;" at the top of thing.rs then you get an error saying:
error[E0468]: an extern crate
loading macros must be at the crate root
and if you search you find this stack-overflow question: How do you import macros in submodules in Rust? - Stack Overflow but nothing there works.
If I move the "#[macro_use] extern crate log;" to the top of lib.rs, then I get
error: cannot find macro trace!
in this scope
when it hits the use of 'trace!'.
If I add an additional "#[macro_use] extern crate log;", so it is at the top of both thing.rs and lib.rs, then I get the original error - it doesn't want the macros_use annotation at the top of the sub-module. If I remove that annotation and just have "extern crate log", that doesn't work. Some searching reveals that maybe I need to "use" something instead of "extern crate" in thing.rs, but at this stage I'm just frustrated - it's time to ask for help.
I have no good mental model for how crates/modules work in rust. They cause me WAY more pain than borrowing (which I really don't find hard at all). In fact, I don't want to use modules here at all - I only have one function - but I'm being forced to use a module to make that function public.
Help. What is the easy way to make a one-function example ffi library that uses a macro?
Thanks.