超實用~使用 Xcode 編譯 Swift 源碼

使用Xcode編譯

安裝編譯工具

首先,使用Homebrew安裝cmakenijia

brew install cmake ninja

我的電腦本地編譯工具環(huán)境為

Xcode: 12.3

swift版本:Apple Swift version 5.3.2 (swiftlang-1200.0.45 clang-1200.0.32.28)
Target: x86_64-apple-darwin19.6.0

cmake: cmake version 3.18.0

python: Python 2.7.16

拉取源碼

在家目錄新建文件夾swift-source,并從Github拉取源碼,拉取的源碼版本要和你本地的Swift版本一致。

git clone --branch swift-5.3.2-RELEASE git@github.com:apple/swift.git

拉取編譯源碼所需依賴

./swift/utils/update-checkout --tag swift-5.3.2-RELEASE --clone

這一步需要翻墻,會拉取編譯的所有依賴。

圖片

編譯

./swift/utils/build-script --release-debuginfo --debug-swift-stdlib -x --skip-ios --skip-watchos --skip-tvos --swift-darwin-supported-archs="x86_64"

使用build-script進行編譯,build-script是蘋果官方提供的編譯腳本。

  • --release-debuginfo: 編譯出帶有RelWithDebInfo環(huán)境變量的工程,類似于DebugRelease模式,RelWithDebInfo會優(yōu)化一部分,但同時保留調(diào)試信息。
  • --debug-swift-stdlib: 編譯帶有調(diào)試信息的Swift標準庫,如果想調(diào)試Swift編譯器,可以使用--debug-swift。
  • -x: 等價于--xcode,會生成一個Swift.xcodeproj工程。
  • --skip-ios: 跳過ios,這樣可以編譯的更快,只編譯macos程序。
  • --swift-darwin-supported-archs="x86_64": 只編譯x86_64架構(gòu),加快編譯速度。

可以使用./swift/utils/build-script --help來查看更多編譯選項。

編譯完成后,會生成Xcode-RelWithDebInfoAssert+stdlib-DebugAssert文件夾,如圖所示

圖片

源碼調(diào)試設置

1,在Swift.xcodeproj工程里面,新建Target LYCSwift,并把編譯好的RelWithDebInfo環(huán)境變量下的ALL_BUILDTarget作為依賴

圖片

2,將LYCSwifttarget中的Enable Handened Runtime設置為NO

圖片

源碼調(diào)試

main.swift中,添加如下代碼

圖片

HeapObject.cpp中設置斷點

圖片

RelWithDebInfo模式下,運行LYCSwift,這樣我們就可以用Xcode調(diào)試源碼了。

圖片

問題

1,but none of these is a common dependency of the other(s). This is not allowed by the Xcode "new build system".

這是因為,一開始我的cmake版本是3.19.2,在3.19.0之后,cmake會默認選擇 "new build system",所以,我把cmake回退到了3.18.0版本。在編譯的時候,使用之前的構(gòu)建系統(tǒng),可以在 CMake[1]網(wǎng)站下載相應版本的dmg,并安裝,然后使用sudo "/Applications/CMake.app/Contents/bin/cmake-gui" --install鏈接到/usr/local/bin目錄。

圖片

2,修改完構(gòu)建系統(tǒng)的問題之后,又出現(xiàn)了如下問題:

圖片

不知道為什么會出現(xiàn)這個問題,此時,Swift.xcodeproj工程已生成,我們打開工程,手動選擇ALL_BUILDscheme,

圖片

選中ReWithDebInfo 繼續(xù)編譯即可。

圖片

3,當編譯ALL_BUILD工程時,又出現(xiàn)了 clang: error: no such file or directory: '/Users/mac/swift-source/build/Xcode-ReleaseAssert+stdlib-DebugAssert/cmark-macosx-x86_64/src/RelWithDebInfo/libcmark.a'的問題。

圖片

我們打開cmark-macosx-x86_64/cmark.xcodeproj,選擇cmarkscheme,編譯一下,編譯成功之后,繼續(xù)編譯Swift.xcodeproj即可。

4,最后遇見了clang: error: no such file or directory: '/Users/mac/swift-source/build/Xcode-ReleaseAssert+stdlib-DebugAssert/swift-macosx-x86_64/stdlib/public/runtime/Swift.build/RelWithDebInfo/swiftRuntime-macosx-x86_64.build/Objects-normal/arm64/AnyHashableSupport.o'的問題,這里面,只有x86_64架構(gòu)的編譯文件,因為我的電腦是Intel的芯片,我不需要arm64,為了解決編譯報錯問題,就拷貝一份x86_64文件夾,并改名為arm64即可。

圖片

如果覺得有收獲請按如下方式給個 愛心三連:??:點個贊鼓勵一下。??:收藏文章,方便回看哦!。??:評論交流,互相進步!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容