有條件地編譯內聯彙編
使用條件編譯來確保程式碼僅針對預期的指令集(例如 x86
)進行編譯。否則,如果為其他體系結構(如 ARM 處理器)編譯程式,則程式碼可能會無效。
#![feature(asm)]
// Any valid x86 code is valid for x86_64 as well. Be careful
// not to write x86_64 only code while including x86 in the
// compilation targets!
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn do_nothing() {
unsafe {
asm!("NOP");
}
}
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64"))]
fn do_nothing() {
// This is an alternative implementation that doesn't use any asm!
// calls. Therefore, it should be safe to use as a fallback.
}