Xcrun swift at the command line will generate <unknown>: 0: error: could not load the shared library
My goal is to try running my Swift program as a script. If the whole program is autonomous, you can run it like this:
% xcrun swift hello.swift where hello.swift
import Cocoa println("hello") However, I want to take one step beyond this and include a quick module where I can import other classes, funcs, etc.
So let's say we have a really nice class that we want to use in GoodClass.swift
public class GoodClass { public init() {} public func sayHello() { println("hello") } } I like to import this goodie into my hello.swift:
import Cocoa import GoodClass let myGoodClass = GoodClass() myGoodClass.sayHello() First I create the module .o, lib <>. a .swift by doing the following:
% xcrun swiftc -emit-library -emit-object GoodClass.swift -sdk $(xcrun --show-sdk-path --sdk macosx) -module-name GoodClass % ar rcs libGoodClass.a GoodClass.o % xcrun swiftc -emit-module GoodClass.swift -sdk $(xcrun --show-sdk-path --sdk macosx) -module-name GoodClass Then, finally, I'm ready to run hello.swift (as if it were a script):
% xcrun swift -I "./" -L "./" -lGoodClass -sdk $(xcrun --show-sdk-path --sdk macosx) hello.swift But I got this error:
<unknown>: 0: error: failed to load libGoodClass shared library
What does it mean? What am I missing. If I continue and make a link / compilation similar to what you do for C / C ++:
% xcrun swiftc -o hello -I "./" -L "./" -lGoodClass -sdk $(xcrun --show-sdk-path --sdk macosx) hello.swift % ./hello Then everything will be happy. I think I could live with this, but still want to understand this error with a shared library.
Here is a reformatted, simplified bash script to create your project. Your use of -emit-object and subsequent conversion is not required. Your command does not generate the libGoodClass.dylib file, which is necessary for the -lGoodClass linker when running xcrun swift -I "./" -L "./" -lGoodClass -sdk $(xcrun --show-sdk-path --sdk macosx) hello.swift . You also did not specify a module to communicate with -module-link-name .
This works for me:
#!/bin/bash xcrun swiftc \ -emit-library \ -module-name GoodClass \ -emit-module GoodClass.swift \ -sdk $(xcrun --show-sdk-path --sdk macosx) xcrun swift -I "." -L "." \ -lGoodClass \ -module-link-name GoodClass \ -sdk $(xcrun --show-sdk-path --sdk macosx) hello.swift