Is it possible that I can get an output like this: (abbr)
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}
int main() {
factorial(10);
}
i.e. without machine code. I looked at the man page, and couldn't find an option like that.
Is there another tool which can show me the assembly intermingled with the source code? I know that many IDEs like visual studio has this feature built in.Btw, one way is using
and then call main.o
and that produces what I need, but it is too much work to start gdb and run that command.
I have a simple cpp program in main.cpp: int factorial(int n) { int result = 1; for (int i = 1; i <= n; ++i) { result *= i; } return result; } int main() { factorial(10); } One can ...
0000000000000000 <_Z9factoriali>:
int factorial(int n) {
0: 55 push rbp
1: 48 89 e5 mov rbp,rsp
4: 89 7d ec mov DWORD PTR [rbp-0x14],edi
int result = 1;
7: c7 45 fc 01 00 00 00 mov DWORD PTR [rbp-0x4],0x1
for (int i = 1; i <= n; ++i) {
e: c7 45 f8 01 00 00 00 mov DWORD PTR [rbp-0x8],0x1
15: 8b 45 f8 mov eax,DWORD PTR [rbp-0x8]
18: 3b 45 ec cmp eax,DWORD PTR [rbp-0x14]
1b: 7f 0f jg 2c <_Z9factoriali+0x2c>
result *= i;
1d: 8b 45 fc mov eax,DWORD PTR [rbp-0x4]
20: 0f af 45 f8 imul eax,DWORD PTR [rbp-0x8]
24: 89 45 fc mov DWORD PTR [rbp-0x4],eax
for (int i = 1; i <= n; ++i) {
27: ff 45 f8 inc DWORD PTR [rbp-0x8]
2a: eb e9 jmp 15 <_Z9factoriali+0x15>
}
return result;
2c: 8b 45 fc mov eax,DWORD PTR [rbp-0x4]
}
2f: 5d pop rbp
30: c3 ret
From manpage of objdump,
0000000000000000 <_Z9factoriali>:
int factorial(int n) {
push rbp
mov rbp,rsp
mov DWORD PTR [rbp-0x14],edi
int result = 1;
mov DWORD PTR [rbp-0x4],0x1
for (int i = 1; i <= n; ++i) {
mov DWORD PTR [rbp-0x8],0x1
mov eax,DWORD PTR [rbp-0x8]
cmp eax,DWORD PTR [rbp-0x14]
jg 2c <_Z9factoriali+0x2c>
result *= i;
mov eax,DWORD PTR [rbp-0x4]
imul eax,DWORD PTR [rbp-0x8]
mov DWORD PTR [rbp-0x4],eax
for (int i = 1; i <= n; ++i) {
inc DWORD PTR [rbp-0x8]
jmp 15 <_Z9factoriali+0x15>
}
return result;
mov eax,DWORD PTR [rbp-0x4]
}
pop rbp
ret
--no-show-raw-insn When disassembling instructions, do not print the instruction bytes. This is the default when --prefix-addresses is used.
So, gdb
should do the trick.disassemble /m func_name
g++ -c -g main.cpp
然后我们可以在此基础上运行 objdump来查看汇编代码和机器代码以及源代码。
objdump -S -M intel --no-show-raw-insn main.o | less
objdump -S -M intel main.o。