c_import
This is a small proc macro crate providing a c_import macro (also a cpp_import macro), which can be used to import C headers into your program. It leverages bindgen, so bindgen needs to be installed in your system. It also works in no_std mode.
Usage
In your Cargo.toml:
# Cargo.toml
[]
= "0.2"
In your Rust source file:
// src/main.rs
use c_importc_import;
c_import!;
If you don't use the --link
directive, you can use a Rust build script:
// build.rs
Using non-system headers is also possible via enclosing the header path with quotation marks:
// src/main.rs
use c_importc_import;
c_import!;
Extra clang arguments
You can pass extra clang arguments as extra arguments to the macro:
// src/main.rs
use c_importc_import;
c_import!;
Similarly you can invoke tools like pkg-config to retrieve cflags and pass them to bindgen:
use c_importc_import;
c_import!;
Macro parameters
- Normal arguments are considered header files.
- Arguments starting with
--link
are used to insert#[link (name = libname)]
attributes to the generated extern functions, this allows linking the libraries without having to explicitly create a build.rs file containingprintln!("cargo:rustc-link-lib=libname");
- Arguments starting with
--
are considered bindgen arguments. - Arguments starting with
-
are considered cflags, such as include paths or defines ("-I" & "-D" respectively). - Arguments starting with
$
are considered shell commands which return cflags, similar to pkg-config.
Usage with C++ headers (limited)
// src/main.rs
use c_import cpp_import;
cpp_import!;
// build.rs
Another example showing how to deal with C++ namespaces:
// src/my_header.hpp
// src/main.rs
use c_import cpp_import;
cpp_import!;
Limitations
- Mostly bindgen limitations:
- with C++ headers.
- with static inline functions.