How does library crates create their own conditional compilation attribute macros?

⚓ rust    📅 2025-05-16    👤 surdeus    👁️ 5      

surdeus

Warning

This post was published 45 days ago. The information described in this article may have changed.

Let us go straight into two examples

  1. Rustversion's
#[rustversion::since(1.33)]
use std::pin::Pin;

and,

  1. Pyo3's
#[cfg(Py_3_7)]
fn function_only_supported_on_python_3_7_and_up() { }

#[cfg(not(Py_3_8))]
fn function_only_supported_before_python_3_8() { }

#[cfg(not(Py_LIMITED_API))]
fn function_incompatible_with_abi3_feature() { }

Basically, what I want to understand is, how can I write an attribute macro like #[rustversion::since(...)] (as in rustversion crate) or to make use of #[cfg(...)] and to imbue new compilation flags, e.g. Py_LIMITED_API (as in pyo3 crate)?

I read the source codes but I don't understand what are the strategies for these two crates when it comes to implementation?

Let's give a concrete usecase, suppose I am interested to provide a library crate for my company's Rust engineers - to deploy their binaries in different environments, just DEV, UAT and PROD.

How can I write something like #[cfg(DEV)] or #[Env::DEV] to enable conditional compilation according to the environment the binary is built in?

Thank you.

1 post - 1 participant

Read full topic

🏷️ rust_feed