Skip to content

Avoid assigning (wrong) types to constants using #define #2120

@JanBeh

Description

@JanBeh

Input C/C++ Header

#define MYCONST 2

Bindgen Invocation

$ bindgen input.h

Actual Results

/* automatically generated by rust-bindgen 0.59.1 */

pub const MYCONST: u32 = 2;

Expected Results

It would be better to generate something like

macro_rules! MYCONST { () => { 2 }; }

and to expect users to use MYCONST!() instead of MYCONST.

Reasoning

Constants using #define in a C header file do not have a type. They are inserted by the preprocessor as a literal where needed. Translating them to a Rust const with a type (u32, i32, or others) may lead to unexpected results. For example, i32 can be interchaged with std::os::raw::c_int on most platforms. But code that relies on that will not be portable. See discussion on Rust Users Forum "Interfacing C code with bindgen: #define and types".

Migration

Maybe it can be made possible to enable this new described behavior with an option that is not enabled by default; or the generated macro_rules!s could be created in addition to the consts (unless being switched off by an option).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions