build.rs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 {
  49. unimplemented!()
  50. }
  51. // The bindgen::Builder is the main entry point
  52. // to bindgen, and lets you build up options for
  53. // the resulting bindings.
  54. let bindings = bindgen::Builder::default()
  55. // The input header we would like to generate
  56. // bindings for.
  57. .header("src/randomx.h")
  58. // Tell cargo to invalidate the built crate whenever any of the
  59. // included header files changed.
  60. .parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
  61. // Finish the builder and generate the bindings.
  62. .generate()
  63. // Unwrap the Result and panic on failure.
  64. .expect("Unable to generate bindings");
  65. // Write the bindings to the $OUT_DIR/bindings.rs file.
  66. let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
  67. bindings
  68. .write_to_file(out_path.join("bindings.rs"))
  69. .expect("Couldn't write bindings!");
  70. }