7

我的目标是尝试像脚本一样运行我的 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

然后一切都很幸福。我想我可以忍受,但仍然想了解共享库错误。

4

1 回答 1

6

这是一个重新格式化的简化 bash 脚本,用于构建您的项目。您的使用-emit-object和随后的转换是不必要的。您的命令不会导致生成 libGoodClass.dylib 文件,这是-lGoodClass您运行时链接器需要的参数xcrun swift -I "./" -L "./" -lGoodClass -sdk $(xcrun --show-sdk-path --sdk macosx) hello.swift。您也没有指定要链接到的模块-module-link-name

这对我有用:

#!/bin/bash

xcrun swiftc \
    -emit-library \
    -module-name GoodClass \
    -emit-module GoodClass.swift \
    -sdk $(xcrun --show-sdk-path --sdk macosx)

xcrun swift -I "." -L "." \
    -lGoodClass \
    -module-link-name GoodClass \
    -sdk $(xcrun --show-sdk-path --sdk macosx) hello.swift
于 2014-11-20T19:03:14.757 回答