调试x86-64汇编程序时GDB提示“无法识别文件格式”问题求助
Got it, let's break down why you're hitting this error and fix it right away. The core issue is simple: you're trying to debug your plain-text assembly source file instead of the actual executable binary generated by your linker!
Here's what's going wrong in your current workflow:
- When you run
nasm -felf64 hello_world, it creates an object filehello_world.o(this is not an executable yet) - When you run
ld hello_world.owithout specifying an output name,lddefaults to spitting out an executable calleda.out—nothello_world - So when you run
gdb hello_world, you're pointing GDB at your original assembly source (which is whyfile hello_worldsays it's ASCII text)
Step-by-Step Fix
Recompile and link with explicit output filenames
Use the-oflag to tell both tools exactly what to name their outputs—this eliminates confusion between source, object, and executable files:# Assemble the source into an object file nasm -felf64 hello_world -o hello_world.o # Link the object file into a named executable ld hello_world.o -o hello_worldPro tip: If your assembly file uses a
.asmsuffix (likehello_world.asm), include it in thenasmcommand to make your intent even clearer.Verify the executable format
Runfile hello_worldagain—you should see output like this, confirming it's a valid 64-bit ELF executable:ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not stripped
Launch GDB on the correct executable
Now you can debug the actual binary without format errors:gdb ./hello_world
Quick Tip to Avoid This Later
Always double-check which file you're targeting with GDB. Run ls -l in your directory—you'll spot the difference instantly:
- The source file will be small (just a few lines of text)
- The object file (
hello_world.o) will be slightly larger - The executable (
hello_world) will be bigger and have executable permissions (marked with anxin the permissions column)
内容的提问来源于stack exchange,提问作者Sharon1111

