![](/img/trans.png)
[英]Different behavior of double and int64_t conversion on new Apple silicon (arm64) vs. x86_64
[英]Why does my native application compiled on Apple Silicon sometimes build as arm64 and sometimes build as x86_64?
我有一個基本的 C 程序:
#include <stdio.h>
int main() {
printf("Hello, world!\n");
}
當我在 Apple Silicon 設備上直接使用cc
編譯它時,它會生成一個arm64
可執行文件:
% cc hello.c -o hello
% file hello
hello: Mach-O 64-bit executable arm64
% ./hello
Hello, world!
但是,當我通過諸如 CMake 或 Ninja 之類的構建系統構建它時,它會生成一個 x86_64 二進制文件:
% ./my-build-system
% file hello
hello: Mach-O 64-bit executable x86_64
我已經驗證構建腳本運行的命令與我自己運行的命令相同。 如果我復制並粘貼命令並自己運行它,則生成的可執行文件又是 arm64。
當您的構建命令不包含要構建的架構的特定標志時,Apple 提供的編譯器工具(如cc
根據調用進程的架構執行某種自省。 這意味着,如果您的構建系統尚未針對arm64
進行本機編譯,您可能會看到這種行為,因為編譯器會假設您要針對 x86_64 進行構建!
您可以通過使用arch
工具在 x86_64 模式下運行cc
可執行文件來證明這一點:
% arch -x86_64 cc hello.c -o hello
% file hello
hello: Mach-O 64-bit executable x86_64
作為一種變通方法,您可以引入一個始終重置為本機架構的 shim 編譯器。 將其保存為force-arm64-cc
並使其可執行:
#!/usr/bin/env bash
# Note we are using arm64e because `cc` does not have an arm64 binary!
exec arch -arm64e cc "$@"
然后,您可以使用此墊片代替cc
:
% CC=$PWD/force-arm64-cc ./my-build-system
% file hello
hello: Mach-O 64-bit executable arm64
正確的長期解決方案是在編譯時指定目標架構:
% arch -x86_64 cc -arch arm64 hello.c -o hello
% file hello
hello: Mach-O 64-bit executable arm64
但是,當您重建二進制文件時,這當前會生成一個偽造的可執行文件,這在編輯-編譯-運行循環中很常見:
% ./hello
zsh: killed ./hello
也可以看看:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.