2010-10-01 290 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