首页 > 解决方案 > 在 Windows 中将程序集与 ld 链接

问题描述

我有这个“你好世界!” 用汇编编写的程序(NASM 语法):

; hello.asm
global _start

extern GetStdHandle
extern WriteFile

section .text
_start:
    push dword -11
    call GetStdHandle
    sub esp, 4
    mov ebx, esp
    push dword 0
    push ebx
    push message_length
    push message
    push eax
    call WriteFile
    add esp, 4
    xor eax, eax
    ret

section .data
    message: db `Hello world!\r\n`
    message_length equ $ - message

我尝试将目标文件与 MinGW 链接,ld但我无法让它工作:

nasm -f win32 hello.asm -o hello.obj
ld -mi386pe hello.obj -o hello.exe -lkernel32

的输出ld是:

ld: cannot find -lkernel32

尝试将目标文件与 GoLink 链接会成功:

nasm -f win32 hello.asm -o hello.obj
golink /entry _start /console hello.obj -o hello.exe kernel32.dll

GoLink 的输出是:

GoLink.Exe Version 1.0.3.0  Copyright Jeremy Gordon 2002-2018   info@goprog.com
Output file: hello.exe
Format: Win32   Size: 2,048 bytes

程序运行良好:

> hello
Hello world!

>

如何ld在 Windows 下使用链接目标文件?请注意,我不想链接到 CRT,因为我没有使用它。

这是我失败的尝试及其输出:

> ld -mi386pe hello.obj -o hello.exe -lkernel32
ld: cannot find -lkernel32

> ld -mi386pe hello.obj -o hello.exe -LC:\Windows\System32 -lkernel32
ld: skipping incompatible C:\Windows\System32/kernel32.dll when searching for -lkernel32
ld: skipping incompatible C:\Windows\System32/kernel32.dll when searching for -lkernel32
ld: cannot find -lkernel32

> ld -mi386pe hello.obj -o hello.exe -LC:\Windows\SysWOW64 -lkernel32
ld: hello.obj:hello.asm:(.text+0x3): undefined reference to `GetStdHandle'
ld: hello.obj:hello.asm:(.text+0x18): undefined reference to `WriteFile'

另外,如果我将名称装饰为_GetStdHandle@4and ,则输出_WriteFile@20

> ld -mi386pe hello.obj -o hello.exe -LC:\Windows\SysWOW64 -lkernel32
ld: warning: resolving _GetStdHandle@4 by linking to _GetStdHandle
Use --enable-stdcall-fixup to disable these warnings
Use --disable-stdcall-fixup to disable these fixups
ld: warning: resolving _WriteFile@20 by linking to _WriteFile
> hello
Access is denied.
> rem This also gives a popup window which says "This app can't run on your PC"

> ld -mi386pe hello.obj -o hello.exe -LC:\Windows\SysWOW64 --disable-stdcall-fixup -lkernel32
ld: hello.obj:hello.asm:(.text+0x3): undefined reference to `GetStdHandle@4'
ld: hello.obj:hello.asm:(.text+0x18): undefined reference to `WriteFile@20'

> ld -mi386pe hello.obj -o hello.exe -LC:\Windows\SysWOW64 --enable-stdcall-fixup -lkernel32
> hello
Access is denied.

另外,如果我将名称装饰为_GetStdHandleand ,则输出_WriteFile

> ld -mi386pe hello.obj -o hello.exe -LC:\Windows\SysWOW64 -lkernel32
> hello
Access is denied.
> rem It doesn't change if I add --enable-stdcall-fixup or --disable-stdcall-fixup

平台详情:

标签: assemblyx86nasmld

解决方案


推荐阅读