Swift包在Xcode中可构建但swift build命令行执行失败
问题:Swift Package用
swift build报错找不到ICU头文件,Xcode中却能正常构建 我有一个Swift包,Package.swift内容如下:
// swift-tools-version: 5.10 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "nmbr-icu", products: [ .library(name: "nmbr-icu", targets: ["nmbr-icu"]) ], targets: [ // Main NMBR target, contains 1 ObjC++ file (h + mm) .target(name: "nmbr-icu", dependencies: ["ICU"]), // Target to build the ICU framework, an xcframework for the ICU C++ code .binaryTarget(name: "ICU", path: "./ICU.xcframework"), // Test target .testTarget(name: "nmbrTests", dependencies: ["nmbr-icu"]) ], cxxLanguageStandard: .cxx20 )
项目结构如图(https://i.sstatic.net/X9x65ecg.png)。在Xcode中双击Package.swift打开后,能正常构建(CMD+B)和测试(CMD+U),但执行swift build命令时返回错误:
NMBRFormatter.mm:11:10: fatal error: 'unicode/unistr.h' file not found #include <unicode/unistr.h>
请问我遗漏了什么?项目开源地址:https://github.com/kerrmarin/nmbr-icu
解决方法
问题根源
Xcode会自动识别xcframework中的头文件路径,但swift build命令不会做这个自动处理,必须手动在target配置里指定ICU的头文件搜索路径。
修改Package.swift
给nmbr-icu这个target添加cxxSettings,指定头文件的搜索路径。你需要根据ICU.xcframework的实际结构来设置路径,下面是两种可行的方式:
方式1:按平台指定精确路径
这种方式更严谨,避免不必要的路径搜索:
.target( name: "nmbr-icu", dependencies: ["ICU"], cxxSettings: [ .platformSpecific(.macOS, .headerSearchPath("./ICU.xcframework/macos-arm64_x86_64/Headers")), .platformSpecific(.iOS, .headerSearchPath("./ICU.xcframework/ios-arm64/Headers")), .platformSpecific(.iOSSimulator, .headerSearchPath("./ICU.xcframework/ios-arm64_x86_64-simulator/Headers")) ] ),
注意要根据你实际支持的平台,调整xcframework里的平台目录名称。
方式2:通用模糊匹配路径
如果需要快速验证或者平台较多,可以用通配符匹配所有平台的Headers目录:
.target( name: "nmbr-icu", dependencies: ["ICU"], cxxSettings: [ .headerSearchPath("./ICU.xcframework/**/Headers") ] ),
验证修改
保存Package.swift后,重新执行swift build,应该就能正常找到头文件并完成构建了。
另外,你可以先检查ICU.xcframework的目录结构,确认unicode/unistr.h所在的位置,确保headerSearchPath指向的是包含unicode目录的父目录(也就是Headers目录)。
内容的提问来源于stack exchange,提问作者KerrM
相关产品推荐
相关产品推荐

