@@ -72,6 +72,56 @@ Options:
72
72
bindgen!("/usr/include/lua.h", link="lua", builtins=true)
73
73
}
74
74
75
+ ### Using a build script to generate bindings at compile time
76
+
77
+ Due to a known issuewith ` include! ` https://github.com/rust-lang/rfcs/issues/752 when generating
78
+ bindings in a build script and importing them with ` include! ` you'll want to wrap the bindings
79
+ in a module before writing them to a file to avoid triggering the issue with top-level
80
+ attributes in ` include! ` . Some more discussion about this issue can be found here
81
+ https://github.com/Yamakaky/rust-bindgen/issues/359 .
82
+
83
+ ` Cargo.toml `
84
+ ``` rust
85
+ [package ]
86
+ ...
87
+ name = " bindgen_ex"
88
+ build = " build.rs"
89
+
90
+ [build - dependencies ]
91
+ bindgen = " 0.19.0"
92
+ ```
93
+
94
+ ` build.rs `
95
+ ``` rust
96
+ extern crate bindgen;
97
+
98
+ use std :: io :: prelude :: * ;
99
+ use std :: fs :: File ;
100
+
101
+ fn main (){
102
+ let mut bindings = bindgen :: Builder :: new (" my_lib.h" );
103
+ bindings . link (" my_lib" , bindgen :: LinkType :: Static );
104
+ // Generate the bindings to a string so we can wrap them
105
+ // instead of going through the `write_to_file` API.
106
+ let generated_bindings = bindings . generate (). expect (" Failed to generate bindings" );
107
+ // Now open the file we'll write the generated bindings too
108
+ let mut file = File :: create (" my_lib.rs" ). expect (" Failed to open file" );
109
+ // Wrap the bindings in a `pub mod` before writing bindgen's output
110
+ file . write (format! (" pub mod {} {{\ n" , " my_lib" ). as_bytes ()). unwrap ();
111
+ file . write (generated_bindings . as_bytes ()). unwrap ();
112
+ file . write (b " }" ). unwrap ();
113
+ }
114
+ ```
115
+
116
+ ` main.rs `
117
+ ``` rust
118
+ include! (" my_lib.rs" );
119
+
120
+ fn main () {
121
+ my_lib :: example_function ();
122
+ }
123
+ ```
124
+
75
125
[ crates-version-shield ] : https://img.shields.io/crates/v/bindgen.svg?style=flat-square
76
126
[ crates-downloads-shield ] : https://img.shields.io/crates/d/bindgen.svg?style=flat-square
77
127
[ crates-license-shield ] : https://img.shields.io/crates/l/bindgen.svg?style=flat-square
0 commit comments