Skip to content

Commit 8c0c66d

Browse files
amirboudanielocfb
authored andcommitted
Add per-target LIBBPF_SYS_LIBRARY_PATH environment variable to help cross-compilation environments
This solves an issue when cross-compiling an application that uses libbpf-sys in build.rs(Usually via libbpf-cargo). In that case, the libbpf-sys crate is built twice - once for the host triplet (let's say x86_64-unknown-linux-gnu, when compiling build.rs) and once for the target triplet (let's say aarch64-linux-android, when compiling the actual application). If we set `LIBBPF_SYS_LIBRARY_PATH` to a path that contains the libelf for the target triplet, then `build.rs` will link to the incorrect library, failing the build.
1 parent dabd0a5 commit 8c0c66d

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ $ cargo build
4141

4242
- `LIBBPF_SYS_EXTRA_CFLAGS` can be used to pass extra cflags when vendoring libbpf, libz or libelf.
4343
- `LIBBPF_SYS_LIBRARY_PATH`: colon separated paths for the linker to find native libs.
44+
- `LIBBPF_SYS_LIBRARY_PATH_<TARGET_TRIPLE>`: similar to `LIBBPF_SYS_LIBRARY_PATH`, but used to set per-target library path, to help cross-compilation environments. If `LIBBPF_SYS_LIBRARY_PATH_<TARGET_TRIPLE>` and `LIBBPF_SYS_LIBRARY_PATH` are defined, the paths from both will be used, and the "target" paths will have precedence.
4445

4546
### Distribution
4647

build.rs

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -203,11 +203,30 @@ fn main() {
203203
);
204204
println!("cargo:include={}/include", out_dir.to_string_lossy());
205205

206-
println!("cargo:rerun-if-env-changed=LIBBPF_SYS_LIBRARY_PATH");
207-
if let Ok(lib_path) = env::var("LIBBPF_SYS_LIBRARY_PATH") {
208-
for path in lib_path.split(':') {
209-
if !path.is_empty() {
210-
println!("cargo:rustc-link-search=native={}", path);
206+
let global_lib_path = "LIBBPF_SYS_LIBRARY_PATH";
207+
let target_lib_path = format!("{}_{}", global_lib_path, env::var("TARGET").unwrap());
208+
let target_lib_path_underscored = format!(
209+
"{}_{}",
210+
global_lib_path,
211+
env::var("TARGET").unwrap().replace('-', "_")
212+
);
213+
214+
println!("cargo:rerun-if-env-changed={}", global_lib_path);
215+
println!("cargo:rerun-if-env-changed={}", target_lib_path);
216+
println!("cargo:rerun-if-env-changed={}", target_lib_path_underscored);
217+
218+
let lib_paths = vec![
219+
env::var(target_lib_path),
220+
env::var(target_lib_path_underscored),
221+
env::var(global_lib_path),
222+
];
223+
224+
for lib_path in lib_paths {
225+
if let Ok(lib_path) = lib_path {
226+
for path in lib_path.split(':') {
227+
if !path.is_empty() {
228+
println!("cargo:rustc-link-search=native={}", path);
229+
}
211230
}
212231
}
213232
}

0 commit comments

Comments
 (0)