liveBook · Manning

Include! macro

As explained in Refactoring to Rust

The Rust include! macro reads a file's text, parses it as Rust source code, and inserts the resulting code at the macro invocation.

`include!` reads a file, parses its contents as Rust code, and inserts that code at the macro invocation during compilation. It resembles the C/C++ `#include` directive, but it is not the usual way to organize Rust source files. Use the Rust module system for ordinary imports; `include!` is most useful for code generated at build time. section 4.3.1

Compile a generated greeting

A build script reads `GREET_LANG` and writes a Rust `greet()` function into `src/greet.rs`. The executable places `include!("greet.rs");` before `main`, then calls `greet()`. Writing only a language code such as `en` would not work: the included file must contain valid Rust code. section 4.3.1

Generated files need not live beside the source file that includes them. For bindings written to Cargo’s `OUT_DIR`, `env!("OUT_DIR")` obtains the directory at compile time, while `concat!` forms the path. This differs from a build script’s runtime lookup with `std::env::var`. section 4.3.2

include!(concat!(env!("OUT_DIR"), "/nginx.rs"));

The nested macros form the path to a generated `nginx.rs` file so `include!` can compile its bindings into the Rust library. section 4.3.2

How Refactoring to Rust covers it

How deep it goes
Defines its compile-time behavior and works through file placement and path construction; directs ordinary Rust imports to the module system.
Examples
Uses a generated greeting function and bindgen-produced NGINX bindings in Cargo’s OUT_DIR.
What it assumes
Builds from a simple Cargo greeting program before introducing compile-time paths for generated bindings.
What you can do after
Apply it via Cargo build scripts to compile generated Rust code, including bindgen-produced bindings.
How it connects
Connects Cargo build scripts, the Rust module system, bindgen, env!, and concat!.

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.