onemkl-sys 0.5.2

Raw FFI bindings to the C interface of Intel oneAPI Math Kernel Library (oneMKL).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Build script for `onemkl-sys`.
//!
//! Responsibilities:
//! 1. Locate the Intel oneAPI Math Kernel Library installation (headers + libs).
//! 2. Run `bindgen` against `mkl.h` (and any opt-in MPI-dependent headers) with
//!    the right preprocessor defines for the selected interface layer.
//! 3. Emit a link line matching the selected interface / threading / linkage
//!    feature combination.
//!
//! On docs.rs (`DOCS_RS=1`) we skip MKL entirely and copy the vendored
//! `src/vendored_bindings.rs` into `OUT_DIR/bindings.rs` so the crate
//! still produces documentable items without an MKL install or link
//! step. Same path can be opted into elsewhere by exporting
//! `ONEMKL_SYS_USE_VENDORED_BINDINGS=1`.

use std::env;
use std::path::{Path, PathBuf};
use std::process;

fn main() {
    println!("cargo:rerun-if-changed=build.rs");
    println!("cargo:rerun-if-changed=wrapper.h");
    println!("cargo:rerun-if-changed=src/vendored_bindings.rs");
    println!("cargo:rerun-if-env-changed=MKLROOT");
    println!("cargo:rerun-if-env-changed=ONEAPI_ROOT");
    println!("cargo:rerun-if-env-changed=ONEMKL_SYS_INCLUDE_DIR");
    println!("cargo:rerun-if-env-changed=ONEMKL_SYS_LIB_DIR");
    println!("cargo:rerun-if-env-changed=ONEMKL_SYS_OMP_LIB_DIR");
    println!("cargo:rerun-if-env-changed=ONEMKL_SYS_TBB_LIB_DIR");
    println!("cargo:rerun-if-env-changed=DOCS_RS");
    println!("cargo:rerun-if-env-changed=ONEMKL_SYS_USE_VENDORED_BINDINGS");

    if is_docs_only_build() {
        // The vendored bindings were generated for the LP64 interface (`MKL_INT`
        // is `int`). With `ilp64` they would type-check as hundreds of
        // unrelated integer-width errors, so refuse with the real reason.
        if cfg_feature("ilp64") {
            fatal(concat!(
                "the `ilp64` feature needs bindings generated from the ILP64 headers ",
                "(bindgen with -DMKL_ILP64); the vendored bindings used under ",
                "DOCS_RS / ONEMKL_SYS_USE_VENDORED_BINDINGS are LP64-only. ",
                "Unset ONEMKL_SYS_USE_VENDORED_BINDINGS and build with oneMKL installed."
            ));
        }
        use_vendored_bindings();
        return;
    }

    let cfg = Config::from_env();
    cfg.validate_features();

    let mkl = MklPaths::locate(&cfg);
    cfg.emit_links(&mkl);
    cfg.generate_bindings(&mkl);
}

fn is_docs_only_build() -> bool {
    env::var_os("DOCS_RS").is_some() || env::var_os("ONEMKL_SYS_USE_VENDORED_BINDINGS").is_some()
}

/// Copy the vendored bindings into `OUT_DIR` so `lib.rs`'s `include!`
/// works without ever running bindgen or touching the linker.
fn use_vendored_bindings() {
    let out_dir = PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR not set"));
    let src = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set"))
        .join("src")
        .join("vendored_bindings.rs");
    let dst = out_dir.join("bindings.rs");
    std::fs::copy(&src, &dst).unwrap_or_else(|e| {
        fatal(&format!(
            "failed to copy vendored bindings from {} to {}: {e}",
            src.display(),
            dst.display()
        ))
    });
}

/// Resolved feature configuration.
struct Config {
    interface: Interface,
    threading: Threading,
    linkage: Linkage,
    mpi_features: MpiFeatures,
    target_os: String,
    target_env: String,
}

#[derive(Copy, Clone, PartialEq, Eq)]
enum Interface {
    Lp64,
    Ilp64,
}

#[derive(Copy, Clone, PartialEq, Eq)]
enum Threading {
    Sequential,
    IntelOpenMp,
    Tbb,
}

#[derive(Copy, Clone, PartialEq, Eq)]
enum Linkage {
    Dynamic,
    Static,
    /// Single dynamic library (`mkl_rt`).
    Rt,
}

#[derive(Default)]
struct MpiFeatures {
    cluster_sparse_solver: bool,
    cdft: bool,
    scalapack: bool,
    blacs: bool,
    pblas: bool,
}

impl Config {
    fn from_env() -> Self {
        let interface = match (cfg_feature("lp64"), cfg_feature("ilp64")) {
            (true, false) => Interface::Lp64,
            (false, true) => Interface::Ilp64,
            (true, true) => fatal("features `lp64` and `ilp64` are mutually exclusive"),
            (false, false) => {
                fatal("no interface layer selected; enable exactly one of `lp64` or `ilp64`")
            }
        };

        let threading = match (
            cfg_feature("threading-sequential"),
            cfg_feature("threading-intel-openmp"),
            cfg_feature("threading-tbb"),
        ) {
            (true, false, false) => Threading::Sequential,
            (false, true, false) => Threading::IntelOpenMp,
            (false, false, true) => Threading::Tbb,
            (false, false, false) => fatal(
                "no threading layer selected; enable exactly one of \
                 `threading-sequential`, `threading-intel-openmp`, `threading-tbb`",
            ),
            _ => fatal(
                "multiple threading layers selected; enable exactly one of \
                 `threading-sequential`, `threading-intel-openmp`, `threading-tbb`",
            ),
        };

        let linkage = match (
            cfg_feature("link-dynamic"),
            cfg_feature("link-static"),
            cfg_feature("link-rt"),
        ) {
            (true, false, false) => Linkage::Dynamic,
            (false, true, false) => Linkage::Static,
            (false, false, true) => Linkage::Rt,
            (false, false, false) => fatal(
                "no linkage selected; enable exactly one of `link-dynamic`,                  `link-static` or `link-rt`",
            ),
            _ => {
                fatal("features `link-dynamic`, `link-static` and `link-rt` are mutually exclusive")
            }
        };

        let mpi_features = MpiFeatures {
            cluster_sparse_solver: cfg_feature("cluster-sparse-solver"),
            cdft: cfg_feature("cdft"),
            scalapack: cfg_feature("scalapack"),
            blacs: cfg_feature("blacs"),
            pblas: cfg_feature("pblas"),
        };

        Self {
            interface,
            threading,
            linkage,
            mpi_features,
            target_os: env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(),
            target_env: env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default(),
        }
    }

    fn validate_features(&self) {
        if self.linkage == Linkage::Static && self.target_os == "windows" {
            // Static linking on Windows requires /WHOLEARCHIVE handling that
            // we do not yet emit. Surface this clearly.
            eprintln!(
                "cargo:warning=onemkl-sys: link-static on Windows is experimental; \
                 prefer link-dynamic if you hit unresolved external symbols."
            );
        }
    }

    fn is_msvc(&self) -> bool {
        self.target_env == "msvc"
    }

    /// Preprocessor defines passed to bindgen.
    fn clang_defines(&self) -> Vec<&'static str> {
        let mut defs = Vec::new();
        if self.interface == Interface::Ilp64 {
            defs.push("-DMKL_ILP64");
        }
        defs
    }

    fn emit_links(&self, mkl: &MklPaths) {
        println!("cargo:rustc-link-search=native={}", mkl.lib_dir.display());

        if self.linkage == Linkage::Rt {
            // Single dynamic library: `mkl_rt` loads the interface and
            // threading layers at run time (choose them with
            // `MKL_Set_Interface_Layer` / `MKL_Set_Threading_Layer` or
            // the `MKL_INTERFACE_LAYER` / `MKL_THREADING_LAYER`
            // environment variables), so none of the layered libraries
            // are linked.
            if self.mpi_features.cluster_sparse_solver
                || self.mpi_features.cdft
                || self.mpi_features.scalapack
                || self.mpi_features.blacs
                || self.mpi_features.pblas
            {
                fatal("`link-rt` does not support the MPI-dependent domains");
            }
            link("dylib", "mkl_rt");
            if self.target_os != "windows" {
                println!("cargo:rustc-link-lib=dylib=pthread");
                println!("cargo:rustc-link-lib=dylib=m");
                println!("cargo:rustc-link-lib=dylib=dl");
            }
            println!("cargo:include={}", mkl.include_dir.display());
            println!("cargo:lib={}", mkl.lib_dir.display());
            return;
        }

        let suffix = match self.linkage {
            Linkage::Dynamic if self.is_msvc() => "_dll",
            _ => "",
        };
        let kind = match self.linkage {
            Linkage::Dynamic | Linkage::Rt => "dylib",
            Linkage::Static => "static",
        };

        // Interface layer.
        let interface_lib = match self.interface {
            Interface::Lp64 => "mkl_intel_lp64",
            Interface::Ilp64 => "mkl_intel_ilp64",
        };
        link(kind, &format!("{interface_lib}{suffix}"));

        // Threading layer.
        let threading_lib = match self.threading {
            Threading::Sequential => "mkl_sequential",
            Threading::IntelOpenMp => "mkl_intel_thread",
            Threading::Tbb => "mkl_tbb_thread",
        };
        link(kind, &format!("{threading_lib}{suffix}"));

        // Computational core.
        link(kind, &format!("mkl_core{suffix}"));

        // On Linux the three layered MKL shared libs don't record
        // cross-deps in their own DT_NEEDED tags, so GNU ld / rust-lld
        // (default `--as-needed`) strips `mkl_core` from any executable
        // that doesn't reference it directly. That causes runtime
        // failures inside `mkl_intel_*` (`undefined symbol:
        // mkl_blas_dgemm`) and `mkl_core` (`undefined symbol: log`,
        // `cos`). Wrap the layered libs plus libm/pthread/dl in a
        // `--no-as-needed` block so they all end up in DT_NEEDED.
        // Cargo's `rustc-link-arg` only reaches artifacts of this crate
        // (notably the `smoke` integration test in `onemkl-sys/tests/`).
        // Dependents get the same effect from the symbol references in
        // `src/lib.rs` (`keep_layers_needed`), which travel with the rlib.
        if self.target_os == "linux" && self.linkage == Linkage::Dynamic {
            emit_linux_as_needed_wrap(mkl, interface_lib, threading_lib);
        }

        // MPI-dependent additions.
        if self.mpi_features.scalapack {
            let lib = match self.interface {
                Interface::Lp64 => "mkl_scalapack_lp64",
                Interface::Ilp64 => "mkl_scalapack_ilp64",
            };
            link(kind, &format!("{lib}{suffix}"));
        }
        if self.mpi_features.blacs || self.mpi_features.pblas || self.mpi_features.scalapack {
            // Default to MS-MPI on Windows, Intel MPI otherwise. Users can
            // override by linking their own BLACS lib via build-script add-on
            // crates if they need a different MPI flavor.
            let blacs_lib = if self.is_msvc() {
                match self.interface {
                    Interface::Lp64 => "mkl_blacs_msmpi_lp64",
                    Interface::Ilp64 => "mkl_blacs_msmpi_ilp64",
                }
            } else {
                match self.interface {
                    Interface::Lp64 => "mkl_blacs_intelmpi_lp64",
                    Interface::Ilp64 => "mkl_blacs_intelmpi_ilp64",
                }
            };
            // BLACS comes only as a static archive for non-MS-MPI flavors;
            // try with the requested suffix and fall through to no-suffix.
            if self.linkage == Linkage::Dynamic && self.is_msvc() {
                link("dylib", &format!("{blacs_lib}_dll"));
            } else {
                link("static", blacs_lib);
            }
        }
        if self.mpi_features.cdft {
            let cdft = if self.linkage == Linkage::Dynamic && self.is_msvc() {
                "mkl_cdft_core_dll"
            } else {
                "mkl_cdft_core"
            };
            link(
                if self.linkage == Linkage::Dynamic {
                    "dylib"
                } else {
                    "static"
                },
                cdft,
            );
        }

        // Companion runtime libraries for the chosen threading layer.
        match self.threading {
            Threading::Sequential => {}
            Threading::IntelOpenMp => {
                if let Some(dir) = mkl.omp_lib_dir.as_ref() {
                    println!("cargo:rustc-link-search=native={}", dir.display());
                }
                let omp_lib = if self.is_msvc() {
                    "libiomp5md"
                } else {
                    "iomp5"
                };
                println!("cargo:rustc-link-lib=dylib={omp_lib}");
            }
            Threading::Tbb => {
                if let Some(dir) = mkl.tbb_lib_dir.as_ref() {
                    println!("cargo:rustc-link-search=native={}", dir.display());
                }
                let tbb_lib = if self.is_msvc() { "tbb12" } else { "tbb" };
                println!("cargo:rustc-link-lib=dylib={tbb_lib}");
            }
        }

        // Platform runtime libraries.
        if self.target_os != "windows" {
            println!("cargo:rustc-link-lib=dylib=pthread");
            println!("cargo:rustc-link-lib=dylib=m");
            println!("cargo:rustc-link-lib=dylib=dl");
        }

        // Re-export to dependents.
        println!("cargo:include={}", mkl.include_dir.display());
        println!("cargo:lib={}", mkl.lib_dir.display());
    }

    fn generate_bindings(&self, mkl: &MklPaths) {
        let out_dir = PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR not set"));
        let wrapper = build_wrapper(&out_dir, &self.mpi_features);

        let mut builder = bindgen::Builder::default()
            .header(wrapper.to_string_lossy().into_owned())
            .clang_arg(format!("-I{}", mkl.include_dir.display()))
            .clang_args(self.clang_defines())
            .derive_default(true)
            .derive_debug(true)
            .derive_copy(true)
            .layout_tests(false)
            .generate_comments(false)
            .prepend_enum_name(false)
            .default_enum_style(bindgen::EnumVariation::ModuleConsts)
            // Limit bindgen output to declarations sourced from MKL headers
            // (and the umbrella `wrapper.h`). This excludes Windows SDK,
            // libc, MSVC intrinsics, etc. while keeping the entire MKL
            // surface area exposed.
            .allowlist_file(".*[/\\\\]wrapper\\.h")
            .allowlist_file(".*[/\\\\]mkl[_a-z0-9]*\\.h")
            .allowlist_file(".*[/\\\\]i_malloc\\.h")
            .blocklist_type("FILE")
            .blocklist_type("__.*")
            .blocklist_function("__.*");

        if let Ok(extra) = env::var("ONEMKL_SYS_BINDGEN_EXTRA_CLANG_ARGS") {
            for arg in extra.split_whitespace() {
                builder = builder.clang_arg(arg);
            }
        }

        let bindings = builder
            .generate()
            .unwrap_or_else(|e| fatal(&format!("bindgen failed: {e}")));

        let out_path = out_dir.join("bindings.rs");
        bindings
            .write_to_file(&out_path)
            .unwrap_or_else(|e| fatal(&format!("failed to write bindings: {e}")));
    }
}

/// Resolved on-disk locations.
struct MklPaths {
    include_dir: PathBuf,
    lib_dir: PathBuf,
    omp_lib_dir: Option<PathBuf>,
    tbb_lib_dir: Option<PathBuf>,
}

impl MklPaths {
    fn locate(cfg: &Config) -> Self {
        // 1. Explicit override.
        let include_dir = env::var_os("ONEMKL_SYS_INCLUDE_DIR")
            .map(PathBuf::from)
            .filter(|p| p.join("mkl.h").exists());

        let lib_dir = env::var_os("ONEMKL_SYS_LIB_DIR")
            .map(PathBuf::from)
            .filter(|p| p.is_dir());

        let (include_dir, lib_dir) = match (include_dir, lib_dir) {
            (Some(i), Some(l)) => (i, l),
            (i, l) => {
                let candidates = mkl_root_candidates();
                let root = candidates
                    .iter()
                    .find(|p| p.join("include").join("mkl.h").exists())
                    .cloned()
                    .unwrap_or_else(|| {
                        fatal(&format!(
                            "could not locate Intel oneAPI MKL.\n\
                             Tried (in order): MKLROOT, ONEMKL_SYS_INCLUDE_DIR, \
                             ONEAPI_ROOT/mkl/latest, and standard install paths.\n\
                             Set MKLROOT to your MKL install (e.g. \
                             `C:\\Program Files (x86)\\Intel\\oneAPI\\mkl\\latest`).\n\
                             Searched: {:?}",
                            candidates
                        ))
                    });
                let i = i.unwrap_or_else(|| root.join("include"));
                let l = l.unwrap_or_else(|| {
                    let lib = root.join("lib");
                    // Older Linux installs use `lib/intel64`.
                    let intel64 = lib.join("intel64");
                    if intel64.is_dir() { intel64 } else { lib }
                });
                (i, l)
            }
        };

        let omp_lib_dir = env::var_os("ONEMKL_SYS_OMP_LIB_DIR")
            .map(PathBuf::from)
            .or_else(|| find_compiler_lib(cfg));
        let tbb_lib_dir = env::var_os("ONEMKL_SYS_TBB_LIB_DIR")
            .map(PathBuf::from)
            .or_else(|| find_tbb_lib(cfg));

        Self {
            include_dir,
            lib_dir,
            omp_lib_dir,
            tbb_lib_dir,
        }
    }
}

fn mkl_root_candidates() -> Vec<PathBuf> {
    let mut out = Vec::new();
    if let Some(v) = env::var_os("MKLROOT") {
        out.push(PathBuf::from(v));
    }
    if let Some(v) = env::var_os("ONEAPI_ROOT") {
        let root = PathBuf::from(v);
        out.push(root.join("mkl").join("latest"));
    }
    // Standard Windows install.
    if cfg!(windows) {
        for base in [
            "C:/Program Files (x86)/Intel/oneAPI",
            "C:/Program Files/Intel/oneAPI",
        ] {
            out.push(PathBuf::from(base).join("mkl").join("latest"));
            // Also try the most recent versioned install if `latest` is missing.
            if let Ok(entries) = std::fs::read_dir(format!("{base}/mkl")) {
                let mut versions: Vec<_> = entries
                    .flatten()
                    .map(|e| e.path())
                    .filter(|p| p.is_dir() && p.file_name().is_some_and(|n| n != "latest"))
                    .collect();
                // Naive lexicographic sort gives us ascending order; pick the last.
                versions.sort();
                if let Some(latest) = versions.last() {
                    out.push(latest.clone());
                }
            }
        }
    } else {
        for base in ["/opt/intel/oneapi", "/usr/local/intel/oneapi"] {
            out.push(PathBuf::from(base).join("mkl").join("latest"));
        }
    }
    out
}

fn find_compiler_lib(cfg: &Config) -> Option<PathBuf> {
    // Intel OpenMP runtime sits in the `compiler` component, not `mkl`.
    if let Some(v) = env::var_os("ONEAPI_ROOT") {
        let candidate = PathBuf::from(&v)
            .join("compiler")
            .join("latest")
            .join("lib");
        if candidate.is_dir() {
            return Some(candidate);
        }
    }
    if cfg.target_os == "windows" {
        for base in [
            "C:/Program Files (x86)/Intel/oneAPI",
            "C:/Program Files/Intel/oneAPI",
        ] {
            let candidate = PathBuf::from(base)
                .join("compiler")
                .join("latest")
                .join("lib");
            if candidate.is_dir() {
                return Some(candidate);
            }
        }
    }
    None
}

fn find_tbb_lib(cfg: &Config) -> Option<PathBuf> {
    if let Some(v) = env::var_os("ONEAPI_ROOT") {
        let candidate = PathBuf::from(&v).join("tbb").join("latest").join("lib");
        if candidate.is_dir() {
            return Some(candidate);
        }
    }
    if cfg.target_os == "windows" {
        for base in [
            "C:/Program Files (x86)/Intel/oneAPI",
            "C:/Program Files/Intel/oneAPI",
        ] {
            let candidate = PathBuf::from(base).join("tbb").join("latest").join("lib");
            if candidate.is_dir() {
                return Some(candidate);
            }
        }
    }
    None
}

/// Build the umbrella header that bindgen ingests. The default is `mkl.h`,
/// optionally extended with MPI-dependent headers when those features are on.
fn build_wrapper(out_dir: &Path, mpi: &MpiFeatures) -> PathBuf {
    let mut contents = String::from("#include <mkl.h>\n");
    if mpi.cluster_sparse_solver {
        contents.push_str("#include <mkl_cluster_sparse_solver.h>\n");
    }
    if mpi.cdft {
        contents.push_str("#include <mkl_cdft.h>\n");
    }
    if mpi.scalapack {
        contents.push_str("#include <mkl_scalapack.h>\n");
    }
    if mpi.pblas {
        contents.push_str("#include <mkl_pblas.h>\n");
    }
    if mpi.blacs || mpi.pblas || mpi.scalapack {
        contents.push_str("#include <mkl_blacs.h>\n");
    }

    let path = out_dir.join("wrapper.h");
    std::fs::write(&path, contents).expect("failed to write wrapper.h");
    path
}

fn link(kind: &str, name: &str) {
    println!("cargo:rustc-link-lib={kind}={name}");
}

/// Emit the `--no-as-needed` wrap that forces the layered MKL shared
/// libraries and the libm/pthread/dl trio into the binary's DT_NEEDED.
/// See the call site in `Config::emit_links` for the rationale.
fn emit_linux_as_needed_wrap(mkl: &MklPaths, interface_lib: &str, threading_lib: &str) {
    println!("cargo:rustc-link-arg=-Wl,--no-as-needed");
    for name in [interface_lib, threading_lib, "mkl_core"] {
        let so = mkl.lib_dir.join(format!("lib{name}.so"));
        println!("cargo:rustc-link-arg={}", so.display());
    }
    for sys_lib in ["m", "pthread", "dl"] {
        println!("cargo:rustc-link-arg=-l{sys_lib}");
    }
    println!("cargo:rustc-link-arg=-Wl,--as-needed");
}

fn cfg_feature(name: &str) -> bool {
    let var = format!("CARGO_FEATURE_{}", name.replace('-', "_").to_uppercase());
    env::var_os(var).is_some()
}

fn fatal(msg: &str) -> ! {
    eprintln!("error: onemkl-sys: {msg}");
    process::exit(1);
}