从OS X命令行编译和链接Swift加Objective C代码 [英] Compiling and linking Swift plus Objective C code from the OS X command-line

查看:83
本文介绍了从OS X命令行编译和链接Swift加Objective C代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从OS X命令行编译Swift:

Compiling Swift from an OS X command-line:

swift -sdk $(xcrun --show-sdk-path --sdk macosx) test.swift

从命令行编译目标C:

clang -lobjc -framework Foundation -c testObject.m

我可以将-c选项添加到任一编译器以生成.o文件.

I can add the -c option to either compiler to produce .o files.

如何将这两个源文件链接到一个应用程序中?

How can I link these two source files into one app?

还是需要建造?

推荐答案

TL; DR :最好使用Xcode工具,因为有很多工作要做.但是也可以只使用命令行工具.

TL;DR: It's preferable to use the Xcode tooling, since there's a lot of stuff going on. But it's possible to only use command line tools.

我会警告您,这是一个如何编译和运行.m.swift文件(与Cocoa和Swift运行时相关联)的快速而肮脏的示例.我什至没有尝试遵循双方的最佳做法.

I'll warn you that this is a quick and dirty example of how to compile and run a .m and a .swift file, linked against Cocoa and the Swift runtime. I'm not even trying to follow the best practices on either side.

假设您有一个Objective-C类:

Let's assume you have an Objective-C class:

$ cat C.h
#import <Cocoa/Cocoa.h>
@interface C : NSObject
@property (retain) NSString *c;
@end

$ cat C.m
#import "C.h"

@implementation C

- (id)init {
  self = [super init];
  self.c = @"Hello world!";
  return self;
}

@end

您有一个使用该类的Swift文件:

And you have a Swift file that uses that class:

$ cat S.swift
let c = C()

println(c.c)

您只需要将Objective-C和Swift文件分别编译为.o文件:

You just need to compile the Objective-C and Swift files to .o files, separately:

xcrun clang C.m -o C.o -c
# Be sure to import the bridge header (our only header in this example)
xcrun swiftc -c S.swift -import-objc-header C.h -F /System/Library/Frameworks -I/usr/include

如您所见,我们必须手动添加框架和标头路径,以使Swift编译器找到正确的文件(最好是在SDK中而不是在当前安装的文件中查找它们, btw(带有xcrun --show-sdk-path)).

As you can see, we had to manually include the framework and header paths, to have the Swift compiler locate the proper files (it might be best to have it look for them in the SDK, not in the currently installed files, btw (with xcrun --show-sdk-path)).

然后,我们只需要链接它们,即可拉出所有Swift和Objective-C运行时库.由于默认情况下swift拉动Objective-C库,所以我们甚至不需要指定太多:

Then we simply need to link them, pulling all the Swift and Objective-C runtime libs. Since swift by default pulls the Objective-C libraries, we don't even need to specify much:

xcrun swiftc -o app C.o S.o

看,我们的可执行文件已链接,我们可以运行它!

Behold, our executable is linked and we can run it!

$ ./app
Hello world!

这都是非常有趣的,但是我建议不要直接使用这些工具,除非您实际上是为您的项目构建针对它们的项目构建系统,并且有充分的理由不使用Xcode/xcodebuild.

This is all very interesting, but I would advise against using these tools directly unless you're actually making a build system for your project that targets them and have a good reason not to use Xcode/xcodebuild.

这篇关于从OS X命令行编译和链接Swift加Objective C代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆