gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:19:32 35 4
gpt4 key购买 nike

在 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.swiftswift -frontend -c -module-name myprog -primary-file foo.swift main.swiftswiftc -o myprog main.o foo.o

This is a very simple example, for real applications you probably need to importadditional frameworks and set more options. It can be instructive to check wahtXcode does when building a project, the full compiler and linker outputcan be found in the Report navigator.

See also SWIFT MAKEFILES – TAKE 2for 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 inseparate 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/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com