[][src]Crate cpp

This crate cpp provides macros that allow embedding arbitrary C++ code.


This crate must be used in tandem with the [cpp_build]((https://docs.rs/cpp_build) crate. A basic Cargo project which uses these projects would have a structure like the following:

|-- Cargo.toml
|-- src
    |-- lib.rs
|-- build.rs

Where the files look like the following:


build = "build.rs"

cpp = "0.5"

cpp_build = "0.5"


extern crate cpp_build;

fn main() {


This example is not tested
extern crate cpp;

    #include <stdio.h>

fn main() {
    unsafe {
        cpp!([] {
            printf("Hello, World!\n");

Build script

Use the cpp_build crates from your build.rs script. The same version of cpp_build and cpp crates should be used. You can simply use the cpp_build::build function, or the cpp_build::Config struct if you want more option.

Behing the scene, it uses the cc crate.

Using external liraries

Most likely you will want to link against external libraries. You need to tell cpp_build about the include path and other flags via cpp_build::Config and you need to let cargo know about the link. More info in the cargo docs.

Your build.rs could look like this:

fn main() {
    let include_path = "/usr/include/myexternallib";
    let lib_path = "/usr/lib/myexternallib";
    println!("cargo:rustc-link-search={}", lib_path);

(But you probably want to allow to configure the path via environment variables or find them using some external tool such as the pkg-config crate, instead of hardcoding them in the source)


As with all procedure macro crates we also need to parse Rust source files to extract C++ code. That leads to the fact that some of the language features might not be supported in full. One example is the attributes. Only a limited number of attributes is supported, namely: #[path = "..."] for mod declarations to specify an alternative path to the module file and #[cfg(feature = "...")] for mod declarations to conditionally include the module into the parsing process. Please note that the latter is only supported in its simplest form: straight-forward feature = "..." without any additional conditions, cfg! macros are also not supported at the moment.



This macro is used to embed arbitrary C++ code.


This macro allows wrapping a relocatable C++ struct or class that might have a destructor or copy constructor, implementing the Drop and Clone trait appropriately.