【问题标题】:nasm - Can't link object file with ld on macOS Mojavenasm - 无法在 macOS Mojave 上将目标文件与 ld 链接
【发布时间】:2019-03-20 16:37:56
【问题描述】:

我正在尝试组装一个简单的 Hello World,它在以前的 macOS 版本中运行良好:

        global   start
        section  .text
start:  mov      rax, 0x02000004
        mov      rdi, 1
        mov      rsi, msg
        mov      rdx, 13
        syscall
        mov      rax, 0x02000001
        xor      rdi, rdi
        syscall

        section  .data
msg:    db       "Hello world!", 10

然后我像以前一样使用nasmld

$ nasm -f macho64 hello.asm
$ ld hello.o -o hello

但是ld 给了我以下错误:

ld: warning: No version-min specified on command line
Undefined symbols for architecture x86_64:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for inferred architecture x86_64

我尝试将start 切换为_main,但得到以下结果:

ld: warning: No version-min specified on command line
ld: dynamic main executables must link with libSystem.dylib for inferred architecture x86_64

甚至不知道这可能意味着什么。

【问题讨论】:

  • 这就是你通常链接cc hello.o -o hello的原因,因为C编译器知道如何将目标文件链接到可执行文件中。顺便说一句,您应该使用lea rdi, [rel msg],而不是需要运行时重定位的mov rdi, imm64 绝对形式。

标签: macos assembly nasm ld


【解决方案1】:

在 macOS 11.2 中我使用过:

ld hello.o -L /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/lib -lSystem

【讨论】:

    【解决方案2】:

    ld 需要-lSystem 标志来防止它抛出这个错误。它还需要-macosx_version_min 来删除警告。使用ld 的正确方法是:ld hello.o -o hello -macosx_version_min 10.13 -lSystem

    更新 在 macOS 11 及更高版本上,您还需要传递 -L/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib 以便它正确定位 -lSystem 库。如果需要,您可以使用-L$(xcode-select -p)/SDKs/MacOSX.sdk/usr/lib 动态评估正确的路径。

    【讨论】:

    【解决方案3】:

    更简单的答案。 ld 默认为动态链接并尝试加载正在寻找 maincrt1。所以指定静态链接。

    % ld -e start -static hello.o -o hello
    % ./hello
    Hello world!
    

    【讨论】:

      【解决方案4】:

      除了上面的@Verloren 答案 (https://stackoverflow.com/a/52830915/1189569)

      我在使用 macOS Big Sur (macOS 11.1) 时遇到问题,其中标志 -lSystem 无法找到 libSystem.dylib,并出现错误

      ld: library not found for -lSystem
      

      我发现了 macOS Big Sur,引用自链接: https://developer.apple.com/documentation/macos-release-notes/macos-big-sur-11_0_1-release-notes

      macOS Big Sur 11.0.1 中的新功能,系统附带内置动态 所有系统提供的库的链接器缓存。作为这一变化的一部分, 文件系统上不再存在动态库的副本。 尝试通过查找来检查动态库是否存在的代码 对于路径中的文件或枚举目录将失败...

      动态库的所有副本都不位于usr/lib/ 和类似位置,因此默认情况下找不到标志-lSystem

      解决方案是更新/安装最新版本的命令行工具(如果尚未安装的话),并将ld 命令的标志-L 设置为/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib

      所以完整的命令看起来像这样:

      ld hello.o -o hello -macosx_version_min 11.0 -L /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib -lSystem
      

      【讨论】:

      • 谢谢,这真的很有用。
      猜你喜欢
      • 2019-03-03
      • 2019-05-08
      • 2012-12-19
      • 1970-01-01
      • 2013-12-17
      • 2018-11-18
      • 1970-01-01
      • 2020-02-11
      • 1970-01-01
      相关资源
      最近更新 更多