From 23b12a57e220967acafe59f65d7599daa6fee646 Mon Sep 17 00:00:00 2001 From: Corbin Crutchley Date: Tue, 27 Jan 2026 23:57:37 -0800 Subject: [PATCH] chore: conditionally call code via OS build-time changes --- .gitignore | 3 ++- build.rs | 4 ++++ hello/hello.c | 14 ++++++++++++++ hello/hello.h | 1 + src/main.rs | 19 +++++++++++++++++-- 5 files changed, 38 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 6b39d31..8815d3b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /target -.idea/ \ No newline at end of file +.idea/ +.DS_Store \ No newline at end of file diff --git a/build.rs b/build.rs index 21e0206..a0ed8da 100644 --- a/build.rs +++ b/build.rs @@ -3,6 +3,10 @@ use std::{env, path::PathBuf}; fn main() { let target = env::var("TARGET").unwrap(); + // Re-run this build script if the C source or header changes + println!("cargo:rerun-if-changed=hello/hello.c"); + println!("cargo:rerun-if-changed=hello/hello.h"); + cc::Build::new().file("hello/hello.c").compile("hello"); let bindings = bindgen::builder() diff --git a/hello/hello.c b/hello/hello.c index a7e61c7..ec4b9ba 100644 --- a/hello/hello.c +++ b/hello/hello.c @@ -1,3 +1,17 @@ int hello() { return 42; } + +const char* get_os_name() { +#if defined(_WIN32) || defined(_WIN64) + return "Windows"; +#elif defined(__APPLE__) && defined(__MACH__) + return "macOS"; +#elif defined(__linux__) + return "Linux"; +#elif defined(__unix__) + return "Unix"; +#else + return "Unknown"; +#endif +} diff --git a/hello/hello.h b/hello/hello.h index e8035e8..5613399 100644 --- a/hello/hello.h +++ b/hello/hello.h @@ -1 +1,2 @@ int hello(); +const char* get_os_name(); diff --git a/src/main.rs b/src/main.rs index c638f22..e12addf 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,20 @@ -use rust_multi_os_template::hello; +use std::ffi::CStr; +use rust_multi_os_template::{hello, get_os_name}; fn main() { - println!("Hello, world!{}", unsafe {hello()}.to_string()); + println!("Hello, world! {}", unsafe { hello() }); + + let os_name = unsafe { + CStr::from_ptr(get_os_name()) + }; + println!("Running on: {}", os_name.to_str().unwrap()); + + #[cfg(target_os = "macos")] + println!("Your wallet called—it's crying about that MacBook purchase."); + + #[cfg(target_os = "windows")] + println!("Updating... please wait 3-5 business days."); + + #[cfg(target_os = "linux")] + println!("I use Rust btw."); } -- 2.51.2