1 最后由 cz (2019-03-26 20:25:01) 编辑

主题: mac swift用命令行编译后找不到动态链接库

mac搞的幺蛾子,swift解释执行ok,编译后不可执行,找不到动态链接库
CzMBP:swift cz$ cat helloworld.swift
var hello = "Hello"
var world = "world"
for i in 1...5 {
    print("\(hello) \(world) \(i)")
}
CzMBP:swift cz$ swift helloworld.swift
Hello world 1
Hello world 2
Hello world 3
Hello world 4
Hello world 5
CzMBP:swift cz$ swiftc helloworld.swift
CzMBP:swift cz$ ./helloworld
dyld: Library not loaded: @rpath/libswiftCore.dylib
  Referenced from: /Users/cz/code/swift/./helloworld
  Reason: image not found
Abort trap: 6
CzMBP:swift cz$ otool -L helloworld
helloworld:
    /usr/lib/libobjc.A.dylib (compatibility version 1.0.0, current version 228.0.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.250.1)
    @rpath/libswiftCore.dylib (compatibility version 1.0.0, current version 1001.0.69)
    @rpath/libswiftSwiftOnoneSupport.dylib (compatibility version 1.0.0, current version 1001.0.69)
搜来搜去都是一帮只会用ide的菜鸟

废了老鼻子劲才终于找到一个明白人:https://ruiwchina.wordpress.com/2013/01/17/macos%E4%B8%8A%E7%9A%84executable-path-load-path-%E5%92%8C-rpath/
这个问题源于rpath,这个东西linux也有,用于给程序定制动态链接库的搜寻路径,但macos这个坑货,swift用的库由于不在标准路径下,所以必须要手动指定,不指定则找不到,运行出错。
用命令指定一下即可,用LD_LIBRARY_PATH环境变量也行。
CzMBP:swift cz$ install_name_tool -add_rpath /Applications/Xcode.app/Contents/Frameworks/ helloworld
CzMBP:swift cz$ ./helloworld
Hello world 1
Hello world 2
Hello world 3
Hello world 4
Hello world 5
CzMBP:swift cz$