I am trying to build an application where C++ is the host language and where some functions implemented in Rust are called from C++.
Like all applications, this one, too, has a unique main entry point called main().
As I am new to Rust and CXX Bridge, the problem I'm facing is that all sample code I have found on Google implements this main() function in the Rust part of the project, while I want it implemented in the C++ part of it.
For debugging purposes and as a workaround, I have added a function cppmain() in the C++ code. The Rust main() then calls that cppmain() which in turn calls the Rust function I want to test:
User launches app --> app entered at Rust main() --> C++ cppmain() --> Rust test function
This works for testing but is not what I ultimately need.
What I ultimately want is to remove the Rust main(), and in exchange make cppmain() the official main() of the application (essentially by renaming it to main()):
User launches app --> app entered at C++ main() --> Rust test function
However, I have not succeeded in this. The CXX Bridge seems to expect a main.rs file with the Rust main() inside, and if this is not the case, the build fails (using cargo).
If somebody knows how to solve this problem please let me know. Thanks, Mario
So this is mainly a build question. CXX doesn't have any preference for whether the entrypoint of your application is in Rust or C++ or elsewhere. You mostly find sample code for CXX with main() in Rust because that's all you can do with Cargo, which is a Rust build system.
If you want to build a C++ binary with some functions implemented in Rust, then you need to first build your Rust source as a library and then link it into your C++ binary.
Bigger projects will often have their own multi-language build systems (Bazel, GN, Buck, etc.) that would make this more straightforward, but you can do it yourself just with Cargo or rustc (your Rust toolchain) and a C++ compiler & linker (Clang, GCC, i.e. your C++ toolchain).
See https://doc.rust-lang.org/cargo/reference/cargo-targets.html#the-crate-type-field for the Cargo side of things. You will want a library crate with a crate-type of staticlib, which will produce a .a archive file that you can then link into a larger C++ program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With