在 Objective-C(或一般的 C)中,如果我要有两个文件,例如
main.m:
void foo();
int main (int argc, const char * argv[])
{
foo();
return 0;
}
foo.m:
void foo() {
// do something
}
我什至可以在没有 foo.m 的情况下将 main.m 编译为 main.o,然后编译 foo.m 并与 main.o 链接:
$ clang -c main.m
# later
$ clang main.o foo.m -o FooExecutable
我的理解是 main.m 的第一行中的前向声明或原型(prototype)是使它起作用的原因。
有没有办法在 Swift 中创建相同类型的设置?我还没有找到一种方法来进行相应的 main.swift 编译。
main.swift:
// How do I tell the compiler to trust me that foo() will be implemented?
foo()
foo.swift:
func foo() {
// do something
}
然后:
# This works:
$ swiftc main.swift foo.swift -o FooExecutable
# This doesn't:
$ swiftc -emit-object main.swift
main.swift:3:1: error: use of unresolved identifier 'foo'
foo()
^~~
最佳答案
你不能在 Swift 中声明一个函数而不定义它,编译器 需要“foo.swift”才能编译“main.swift”。
这是一个如何单独编译 Swift 文件然后链接目标文件的示例:
swift -frontend -c -module-name myprog -primary-file main.swift foo.swift swift -frontend -c -module-name myprog -primary-file foo.swift main.swift swiftc -o myprog main.o foo.o
This is a very simple example, for real applications you probably need to import additional frameworks and set more options. It can be instructive to check waht Xcode does when building a project, the full compiler and linker output can be found in the Report navigator.
See also SWIFT MAKEFILES – TAKE 2 for a general GNU Make based solution.
Another option is to compile against a
.swiftmodule and a shared library, compare e.g. How do I import a swift function declared in a compiled .swiftmodule into another swift file?.
Then func foo
must be marked as public
:
foo.swift:
public func foo() {
print("foo")
}
swiftc -emit-module -emit-library -module-name Foo -module-link-name Foo foo.swift
creates Foo.swiftmodule and libFoo.dylib (this can also be done in separate steps). Now main.swift can import the Foo module
main.swift:
import Foo
foo()
swiftc -emit-object -I . main.swift
目标文件可以链接到共享库:
swiftc -o myprog -L . main.o
关于Swift 函数前向声明或原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44530618/