build.rs 2.6 KB

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