Skip to content

Conditionally compiled extern "C" { blocks do not get #if defined( guards #807

@NoraCodes

Description

@NoraCodes

While conditional compilation works fine within extern "C" blocks, annotating an entire extern "C" block with #[cfg()] is valid in Rust, but doesn't work in cbindgen.

For example, for the following Rust project:

# Cargo.toml
[package]
name = "extern_block_conditional"
version = "0.1.0"
authors = ["cbindgen"]

[lib]
name = "extern_block_conditional"
crate-type = ["lib", "dylib"]
features = [ "myfeature" ]
# cbindgen.toml
[defines]
"feature = myfeature" = "DEFINED"
// src/lib.rs
#[repr(C)]
struct Normal {
    x: i32,
    y: f32,
}

#[cfg(feature = "myfeature")]
extern "C" {
    fn foo() -> i32;

    fn bar(a: Normal);
}

I would expect the following C output:

#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>

typedef struct {
  int32_t x;
  float y;
} Normal;

#if defined(DEFINED)
extern int32_t foo(void);

extern void bar(Normal a);
#endif

But in fact, writing this as a test case in this project, the output I see is:

#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>

typedef struct {
  int32_t x;
  float y;
} Normal;

extern int32_t foo(void);

extern void bar(Normal a);

cc @katef

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