Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
679 views
in Technique[技术] by (71.8m points)

macos - Compiling and linking Swift plus Objective C code from the OS X command-line

Compiling Swift from an OS X command-line:

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

Compiling Objective C from the command-line:

clang -lobjc -framework Foundation -c testObject.m

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

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

Or is more needed to build?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...