Nasm中使用ORG指令同时生成带调试符号ELF文件的方法
Got it, let's break down how to solve this problem. The core issue here is that NASM's elf64 target format doesn't support the ORG directive—and for good reason: ELF is a relocatable object format, where final memory addresses are handled by the linker, not the assembler. When you try to mix ORG with -f elf64, NASM throws an error because that directive conflicts with ELF's design of letting the linker adjust addresses later.
Here are two reliable solutions depending on your use case:
Solution 1: Use a Linker Script (Recommended for Most ELF Scenarios)
If your goal is to run the program at a fixed memory address (like kernel code or embedded applications), replace the ORG directive with a linker script that tells the linker where to place your code. This is the cleanest approach for ELF files.
- Update your assembly code: Remove the
ORGline entirely. - Create a linker script (save it as
linker.ld):ENTRY(_start) # Replace with your actual entry point if different SECTIONS { . = 0x100000; # Put your original ORG address here (e.g., 0x8000 for bootloaders) .text : { *(.text) } # Place all text sections at the above address .data : { *(.data) } .bss : { *(.bss) } } - Assemble first, then link:
- Generate the relocatable object file:
nasm -f elf64 -F dwarf -g Main.s -o Main.o - Use
ldwith the linker script to create the final ELF:ld -T linker.ld Main.o -o Main.elf
ORGdirective would have done—but this follows ELF standards, so no errors. - Generate the relocatable object file:
Solution 2: Generate a Binary File, Then Convert to ELF
If your code absolutely relies on ORG (e.g., specific hardcoded address logic that can't be adjusted), you can first build a pure binary file with NASM, then convert it to ELF using objcopy.
- Generate the binary file with ORG intact:
nasm -f bin Main.s -o Main.bin - Convert the binary to ELF64:
objcopy -I binary -O elf64-x86-64 --rename-section .data=.text --set-section-flags .text=code,alloc,load Main.bin Main.elf- The
--rename-sectionflag turns the default.datasection into.text(since this is executable code), and--set-section-flagsmarks it as executable and loadable. - Note: This method loses debug symbols, so it's not ideal if you need to debug your code. Stick with Solution 1 if debugging is important.
- The
Quick Note on Why ORG Fails with ELF64
To keep it simple: ORG tells the assembler "place all following code at memory address X". But ELF object files are designed to be relocatable—they store relative addresses, not fixed ones. The linker's job is to take these relative addresses and map them to final memory locations. Using ORG in an ELF context tries to hardcode addresses, which breaks the relocatable model, hence the error.
内容的提问来源于stack exchange,提问作者Godo

