Translating C to Rust

    (The c2rust refactor tool is also available for refactoring Rust code, see ).

    The translator requires the exact compiler commands used to build the C code. To provide this information, you will need a standard compile_commands.json file. Many build systems can automatically generate this file, as it is used by many other tools, but see for recommendations on how to generate this file for common build processes.

    Once you have a compile_commands.json file describing the C build, translate the C code to Rust with the following command:

    1. c2rust transpile path/to/compile_commands.json

    To generate a Cargo.toml template for a Rust library, add the option:

      Where —main myprog tells the transpiler to use the main method from myprog.rs as the entry point.

      The translated Rust files will not depend directly on each other likenormal Rust modules. They will export and import functions through the CAPI. These modules can be compiled together into a single static Rustlibrary or binary.

      There are several known limitations in thistranslator. The translator will emit a warning and attempt to skip functiondefinitions that cannot be translated.

      The compile_commands.json file can be automatically created usingeither cmake, , or bear.

      When creating the initial build directory with cmake specify-DCMAKE_EXPORT_COMPILE_COMMANDS=1. This only works on projectsconfigured to be built by cmake. This works on Linux and MacOS.

      1. cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1 ...

      intercept-build (part of the ) is recommended for non-cmakeprojects. intercept-build is bundled with clang under tools/scan-build-py buta standalone version can be easily installed via PIP with:

      1. pip install scan-build

      Usage:

      You can also use intercept-build to generate a compilation database for compiling a single C file, for example:

        1. bear <build command>