New projects often need to incorporate existing code.
Sometimes that code is written in a different programming language.
The post covers using the cc-rs crate to compile C,
C++, and ASM code into a Rust project.
Software Versions
Instructions
First, create a new project.
Add cc-rs to the build dependencies.
Cargo.toml Partial Listing
Create a build script.
build.rs
Mixing ASM with either C or C++ is OK, but mixing C and C++ does not work.
Modify src/main.rs to call the external functions.
src/main.rs
Add the C file.
src/hello_c.c
Add the C++ file.
src/hello_cpp.cpp
Add the ASM file.
You will need the version of the .s file for your microarchitecture.
src/hello_asm.s 64-bit ARM for Apple Silicon
src/hello_asm.s x86-64 (Untested)
src/hello_asm.s 32-bit ARM (Untested)
The program should generate the following output.
Inspecting ASM with cargo-show-asm
The cargo-show-asm subcommand can be used to inspect
ASM code.
Install it with the following command.
On macOS, the following command may need to be used instead.
Use the following command to get a list of symbols that can be inspected.
Note that the hello_rust symbol is not listed.
Inspect the code from the main binary using the following command.
Upon inspecting the code, note that main branches to hello_rust.
The function is not inlined and the name is not mangled.
If you know ASM, it might be possible to write a hello_asm routine
using this kind of output.
Generating and Inspecting ASM with the Godbolt Compiler Explorer
If none of the hello_asm routines work for your architecture, the
Godbolt Compiler Explorer is likely a better tool for generating
one than inspecting Rust code.
Select āCā as the language in the lefthand panel, and enter the following code.
In the righthand panel, select a compiler that corresponds to your platform.
For example, armv8-a clang 14.0.0 gives output that is very close to the
version of src/hello_asm.s that was tested on Apple Silicon.