build.rs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. use std::{env, io::Write, path::PathBuf, process::Command};
  2. fn main() {
  3. let n_threads = std::thread::available_parallelism()
  4. .unwrap()
  5. .get()
  6. .to_string();
  7. let cargo_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
  8. let build_dir = &cargo_dir.join("build");
  9. std::fs::create_dir_all(build_dir).unwrap();
  10. env::set_current_dir(build_dir).unwrap();
  11. // Generate CMake cache files
  12. let b = Command::new("cmake")
  13. .arg("-DARCH=native")
  14. .arg("..")
  15. .output()
  16. .expect("Failed to generate Makefile with CMake");
  17. std::io::stdout().write_all(&b.stdout).unwrap();
  18. std::io::stderr().write_all(&b.stderr).unwrap();
  19. assert!(b.status.success());
  20. // Build the library
  21. let b = Command::new("cmake")
  22. .arg("--build")
  23. .arg(".")
  24. .arg("--config")
  25. .arg("Release")
  26. .arg("-j")
  27. .arg(n_threads)
  28. .output()
  29. .expect("Failed to build RandomX library with CMake");
  30. std::io::stdout().write_all(&b.stdout).unwrap();
  31. std::io::stderr().write_all(&b.stderr).unwrap();
  32. assert!(b.status.success());
  33. env::set_current_dir(cargo_dir).unwrap();
  34. // Tell cargo how to find the static library
  35. println!(
  36. "cargo:rustc-link-search=native={}",
  37. build_dir.to_string_lossy()
  38. );
  39. println!("cargo:rustc-link-lib=static=randomx");
  40. let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or("linux".to_string());
  41. let dylib_name = match target_os.as_str() {
  42. "freebsd" | "macos" | "ios" => "c++", // FreeBSD, MacOS, and iOS use "c++",
  43. "windows" => "msvcrt", // Use MSVC runtime on Windows
  44. _ => "stdc++", // Default for other systems (Linux, etc.)
  45. };
  46. println!("cargo:rustc-link-lib=dylib={dylib_name}");
  47. if cfg!(target_os = "windows") {
  48. println!("cargo:rustc-link-lib=advapi32");
  49. }
  50. // The bindgen::Builder is the main entry point
  51. // to bindgen, and lets you build up options for
  52. // the resulting bindings.
  53. let bindings = bindgen::Builder::default()
  54. // The input header we would like to generate
  55. // bindings for.
  56. .header("src/randomx.h")
  57. // Tell cargo to invalidate the built crate whenever any of the
  58. // included header files changed.
  59. .parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
  60. // Finish the builder and generate the bindings.
  61. .generate()
  62. // Unwrap the Result and panic on failure.
  63. .expect("Unable to generate bindings");
  64. // Write the bindings to the $OUT_DIR/bindings.rs file.
  65. let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
  66. bindings
  67. .write_to_file(out_path.join("bindings.rs"))
  68. .expect("Couldn't write bindings!");
  69. }