How to generate a nasm compilable assembly code from c source code on Linux?
If you're lazy: https://github.com/diogovk/c2nasm
There I have a script that does Babken Vardanyan's suggestion automatically.
I find it's a better approach to disassemble the object files rather than use assembly code generated by gcc.
First, generate an object file from your source code:
gcc -fno-asynchronous-unwind-tables -O2 -s -c -o main.o main.c
-fno-asynchronous-unwind-tables
: do not generate unnecessary sections like.eh_frame
-O2
optimizes so the asm isn't horrible. Optionally use-Os
(size over speed) or-O3
(full optimization including auto-vectorization). Also you can tune for a CPU and and use extensions it supports with-march=native
or-march=haswell
or-march=znver1
(Zen)-s
: make smaller executable (strip)-c -o main.o
: compile but don't link, generate an object file calledmain.o
Use objconv to generate
nasm
code:objconv -fnasm main.o
The result will be stored in
main.asm
.The result will be very close to Nasm syntax. However you might need to make some minor tweaks to eliminiate warnings/errors. Simply try to compile it with Nasm
nasm -f elf32 main.asm
and fix the errors/warnings by hand. For example:
- remove the
align=N
andexecute
/noexecute
words from.SECTION
lines. - remove the text
: function
fromglobal
declarations - remove the
default rel
line - remove empty sections if you wish etc
- remove the
Link the resulting
main.o
which generated by Nasm in step 3 using gcc:gcc main.o
You can also link it using ld but it's much harder.