【问题标题】:How to link Windows universal CRT to obj file compiled with nasm如何将 Windows 通用 CRT 链接到用 nasm 编译的 obj 文件
【发布时间】:2017-04-05 18:41:08
【问题描述】:

环境:Windows 10。我碰巧使用 ld 的 MinGW 版本进行链接,但我很乐意使用 Visual Studio link.exe,如果它使事情变得更简单的话。

我在 nasm 中有以下基本程序:

    global  _main
    extern  _printf

    section .text
_main:
    push    message
    call    _printf
    add     esp, 4
    ret
message:
    db  'Hello, World', 10, 0

使用它可以很好地构建

nasm -f win32 test.nasm

尝试将其链接到 windows CRT (ucrt.lib) 时,我收到以下错误:

$ ld -o test.exe test.obj
test.obj:test.nasm:(.text+0x6): undefined reference to `printf'

好的,所以我需要将链接器指向 ucrt 库:

$ ld -o test.exe /c/Program\ Files\ \(x86\)/Windows\ 
Kits/10/Lib/10.0.14393.0/ucrt/x86/ucrt.lib test.obj
test.obj:test.nasm:(.text+0x6): undefined reference to `printf'

尝试使用 Visual Studio 链接器进行等效操作:

d:\Code\nasm>link -out:test.exe -entry:main -subsystem:console test.obj
Microsoft (R) Incremental Linker Version 14.10.25017.0
Copyright (C) Microsoft Corporation.  All rights reserved.

test.obj : error LNK2001: unresolved external symbol _printf
test.exe : fatal error LNK1120: 1 unresolved externals

这引发了几个问题:

  1. 为什么其中一个尝试查找printf 而另一个尝试查找_printf?我知道有一个下划线约定,但两个链接器似乎都不理解它。

  2. 我使用objdump -t 查看 ucrt.lib 文件中的符号。我不会粘贴整个列表,但它包含以下条目:

[ 4](sec 1)(fl 0x00)(ty 0)(scl 2) (nx 0) 0x00000000 __imp____conio_common_vcprintf

[ 5](sec 3)(fl 0x00)(ty 0)(scl 2) (nx 0) 0x00000000 ___conio_common_vcprintf

[ 4](sec 1)(fl 0x00)(ty 0)(scl 2) (nx 0) 0x00000000 __imp____conio_common_vcprintf_p

printf 和 _printf 均未出现在列表中。这是否意味着它不是由该库导出的?如果没有,我应该链接哪个库?

根据this MS article,ucrt.lib 是 c 运行时和 C 标准库的事实上的库。

【问题讨论】:

  • 关于 VS 2015+ 并且缺少一些符号被导出,这个其他答案可能是相关的:stackoverflow.com/questions/33721059/…。 MS 重新设计了库。
  • 感谢您的链接。我尝试手动链接legacy_stdio_definitions.lib 以及 ucrt 并且它有效。旧版库位于完全不同的位置(我的 vs2017 安装目录)。 windows sdk 安装目录中没有等效的迹象。有没有更好的方法将它与我可能需要的 C 标准库中的所有内容联系起来,还是我每次都坚持指定这些子库?
  • 您需要在 VS2015 工具集中包含这些兼容性库。然而,2013 工具集没有重构 C 库,因此您不会遇到这个问题。
  • 好的,感谢您的帮助。如果您想将其作为官方答案,我会接受。
  • 如果您愿意,可以在这里回答您自己的问题。

标签: linker nasm crt universal-crt


【解决方案1】:

感谢 Michael Petch 的评论,看来我需要手动链接 1 个或多个额外的库,这些库位于与 ucrt.lib 库完全不同的位置。与 printf 相关的是 legacy_stdio_definitions.lib,我在 VS2017 安装目录的子目录深处找到了它,而不是在 Windows SDK 安装目录中的 ucrt.lib。

printf 的定义是在 stdio.h 中内联提供的,除非定义了宏 _NO_CRT_STDIO_INLINE,我猜这通常是在 VS 工具链中构建时。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 2016-01-19
    • 2014-04-30
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    相关资源
    最近更新 更多