I have some rust code, that I want to use from both c++ and javascript code. Currently, I have two separate crates that have the main rust crate as a dependency: one exposes c++ API, and the other exposes WASM API. But actually, these two crates are very similar to each other:
As you can see they differ only in attributes and use of the extern keyword.
I would like to have only one crate for both C++ and WASM and just compile it with different compiler options to get the C library or the WASM file.
I'm not sure how to do this in a better way. I do not see a way to do this with just conditional compilation. As for macros, I do not have any experience with that or even any knowledge beyond brief reading of the docs, but I can imagine doing something like:
But adding function args will make it even uglier. Maybe there are better alternatives.
Also, I'm interested in generating some code in another language from rust sources, because the code that will be using this rust code is not in C++ or javascript, but in another language that is compiled to c++ or javascript, so I would like to have bindings to rust code in this language.
You could probably make the contents of the export_func macro a bit prettier, but it is probably the best bet unless you want to go for a proc-macro, which is a lot more complicated.
The cfg will already eliminate one of them very quickly, before doing any analysis on it beyond a simple first parse; I don’t see much need for optimization here.