我的目标是尝试像脚本一样运行我的 Swift 程序。如果整个程序是独立的,你可以像这样运行它:
% xcrun swift hello.swift
hello.swift 在哪里
import Cocoa
println("hello")
但是,我想更进一步,包括 swift 模块,我可以在其中导入其他类、函数等。
所以假设我们有一个非常好的类,我们想在 GoodClass.swift 中使用
public class GoodClass {
public init() {}
public func sayHello() {
println("hello")
}
}
我现在想把这个好东西导入到我的 hello.swift 中:
import Cocoa
import GoodClass
let myGoodClass = GoodClass()
myGoodClass.sayHello()
我首先通过运行这些来生成 .o、lib<>.a、.swiftmodule:
% xcrun swiftc -emit-library -emit-object GoodClass.swift -sdk $(xcrun --show-sdk-path --sdk macosx) -module-name GoodClass
% ar rcs libGoodClass.a GoodClass.o
% xcrun swiftc -emit-module GoodClass.swift -sdk $(xcrun --show-sdk-path --sdk macosx) -module-name GoodClass
最后,我准备运行我的 hello.swift(就好像它是一个脚本一样):
% xcrun swift -I "./" -L "./" -lGoodClass -sdk $(xcrun --show-sdk-path --sdk macosx) hello.swift
但我得到了这个错误:
<未知>:0:错误:无法加载共享库“libGoodClass”
这是什么意思?我错过了什么。如果我继续,并执行类似于 C/C++ 的链接/编译操作:
% xcrun swiftc -o hello -I "./" -L "./" -lGoodClass -sdk $(xcrun --show-sdk-path --sdk macosx) hello.swift
% ./hello
然后一切都很幸福。我想我可以忍受,但仍然想了解共享库错误。