2010-10-01 129 views
13

我想了解阅读由编译器生成的汇编代码。我在哪里以及如何评估从C++生成的汇编代码?C++汇编代码

感谢

回答

3

从您的对象文件:

$ g++ -g -c -Wall yourfile.cpp -o yourfile.o 

然后:

$ gdb yourfile.o 

一旦GDB你可以使用disassemble命令查看生成的程序集。

因此,如果您C++来源:

(gdb) disassemble f 

和输出将是::

Dump of assembler code for function f: 
0x00000000 <f+0>:  push %ebp 
0x00000001 <f+1>:  mov %esp,%ebp 
0x00000003 <f+3>:  mov $0x1,%eax 
0x00000008 <f+8>:  pop %ebp 
0x00000009 <f+9>:  ret 
+0

生成汇编清单的编译器选项比运行反汇编器非常非常多的帮助,因为它会显示出与源代码大会。 – 2010-10-01 15:26:42

+0

@本Voigt:100%与你在那。这并不能让我的回答错误。这只是另一种方式。例如,如果您没有源代码,可能会有所帮助。 – 2010-10-01 15:36:28

3

如果

int f() { return 1; } 

可以在GDB做你正在使用gcc,使用-S参数和编译器的输出不会经过汇编器。

4

您的编译器可能有一个生成汇编代码输出的选项,可以选择与相应的源代码交错。在Microsoft Visual C++ v10中,这是/Fa

或者,只需在调试器中并排查看两个。

但是你看看这个,一定要比较内置和没有优化的版本。看到今天的编译器能够抛弃多少,而不影响程序的运行,这真是太神奇了。

1

对于GCC和objdump。 Using GCC to produce readable assembly?

对于Visual Studio,如果您使用的是IDE,您可以通过修改C/C++“输出文件”属性在项目的性质,变“汇编输出”到“汇编源代码”

这也是Visual C++编译器的'/ Fas'标志。

+0

有我正在寻找的问题! – mkb 2010-10-01 15:27:42

1
//a.cpp 
#include <iostream> 

int main() 
{ 
    std::cout << "hello"; 
} 

海合会可以使用-S选择,即:gcc -S a.cpp产生a.s

(a.s): 

     .file "a.cpp" 
.lcomm __ZStL8__ioinit,1,1 
     .def ___main;  .scl 2;  .type 32;  .endef 
     .section .rdata,"dr" 
LC0: 
     .ascii "hello\0" 
     .text 
.globl _main 
     .def _main; .scl 2;  .type 32;  .endef 
_main: 
     pushl %ebp 
     movl %esp, %ebp 
     andl $-16, %esp 
     subl $16, %esp 
     call ___main 
     movl $LC0, 4(%esp) 
     movl $__ZSt4cout, (%esp) 
     call __ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc 
     movl $0, %eax 
     leave 
     ret 
     .def ___tcf_0;  .scl 3;  .type 32;  .endef 
___tcf_0: 
     pushl %ebp 
     movl %esp, %ebp 
     subl $24, %esp 
     movl $__ZStL8__ioinit, (%esp) 
     call __ZNSt8ios_base4InitD1Ev 
     leave 
     ret 
     .def __Z41__static_initialization_and_destruction_0ii;  .scl 
3;  .type 32;  .endef 
__Z41__static_initialization_and_destruction_0ii: 
     pushl %ebp 
     movl %esp, %ebp 
     subl $24, %esp 
     cmpl $1, 8(%ebp) 
     jne  L3 
     cmpl $65535, 12(%ebp) 
     jne  L3 
     movl $__ZStL8__ioinit, (%esp) 
     call __ZNSt8ios_base4InitC1Ev 
     movl $___tcf_0, (%esp) 
     call _atexit 
L3: 
     leave 
     ret 
     .def __GLOBAL__I_main;  .scl 3;  .type 32;  .endef 
__GLOBAL__I_main: 
     pushl %ebp 
     movl %esp, %ebp 
     subl $24, %esp 
     movl $65535, 4(%esp) 
     movl $1, (%esp) 
     call __Z41__static_initialization_and_destruction_0ii 
     leave 
     ret 
     .section  .ctors,"w" 
     .align 4 
     .long __GLOBAL__I_main 
     .def __ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc; 
.scl 2;  .type 32;  .endef 
     .def __ZNSt8ios_base4InitD1Ev;  .scl 2;  .type 32; 
.endef 
     .def __ZNSt8ios_base4InitC1Ev;  .scl 2;  .type 32; 
.endef 
     .def _atexit;  .scl 2;  .type 32;  .endef