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.
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.
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
And you have a Swift file that uses that class:
$ cat S.swift
let c = C()
println(c.c)
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
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
)).
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!
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
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…