在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!rn`
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:WindowsSystem32 -lkernel32
ld: skipping incompatible C:WindowsSystem32/kernel32.dll when searching for -lkernel32
ld: skipping incompatible C:WindowsSystem32/kernel32.dll when searching for -lkernel32
ld: cannot find -lkernel32
> ld -mi386pe hello.obj -o hello.exe -LC:WindowsSysWOW64 -lkernel32
ld: hello.obj:hello.asm:(.text+0x3): undefined reference to `GetStdHandle'
ld: hello.obj:hello.asm:(.text+0x18): undefined reference to `WriteFile'
另外,如果我将名称装饰为_GetStdHandle@4和,则输出_WriteFile@20:
> ld -mi386pe hello.obj -o hello.exe -LC:WindowsSysWOW64 -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:WindowsSysWOW64 --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:WindowsSysWOW64 --enable-stdcall-fixup -lkernel32
> hello
Access is denied.
另外,如果我将名称装饰为_GetStdHandle和,则输出_WriteFile:
> ld -mi386pe hello.obj -o hello.exe -LC:WindowsSysWOW64 -lkernel32
> hello
Access is denied.
> rem It doesn't change if I add --enable-stdcall-fixup or --disable-stdcall-fixup
平台详情:
- 视窗 10 x64
- NASM 2.14rc15
- 2.32
- 海湾合作委员会 9.2.0
- golink 1.0.3.0