Swift 函数前向声明或原型(prototype)

标签 swift compilation

在 Objective-C(或一般的 C)中,如果我要有两个文件,例如

ma​​in.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 编译。

ma​​in.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/

相关文章:

ios - 从绑定(bind)到多个 UIButtons 的 GestureRecognizer 获取发件人信息

IOS - Swift 4.0 - 使用 Alamofire 的基本访问身份验证 -

swift - displayTransform 调用后图像方向错误

cocoa - Swift 中具有默认值的实例属性 : when are they called?

go - 是否可以预编译 Go 项目并在不同的 Linux 发行版上运行

ios - 从 UITableView - Swift 连续编辑/更改数据的过程是什么

go - 使用动态(config.toml)配置文件发送 Golang 二进制文件

ubuntu - (增量)重建 Debian/Ubuntu 软件包

c++ - 在 Windows 中检索已编译函数的大小

python - 使用 Pygame 的 Py2EXE 编译错误