如何做到这一点呢?

如果我想分析某些东西是如何编译的,我该如何获得发出的程序集代码?


当前回答

就像大家说的,使用-S选项。

如果使用-save-temps选项,还可以获取预处理文件(.i)、程序集文件(.s)和目标文件(*.o)(分别使用-E、-S和-c来获取它们)。

其他回答

使用-S开关:

g++ -S main.cpp

或者也可以用gcc:

gcc -S main.c

还有这个。

下面是在Windows上查看/打印任何C程序的汇编代码的步骤:

在控制台/终端命令提示符中:

Write a C program in a C code editor like Code::Blocks and save it with filename extension .c Compile and run it. Once run successfully, go to the folder where you have installed your GCC compiler and enter the following command to get a ' .s ' file of the ' .c' file cd C:\gcc gcc -S complete path of the C file ENTER An example command (as in my case) gcc -S D:\Aa_C_Certified\alternate_letters.c This outputs a '.s' file of the original '.c' file. After this, type the following command cpp filename.s ENTER Example command (as in my case) cpp alternate_letters.s <enter>

这将打印/输出C程序的整个汇编语言代码。

我在答案中没有看到这种可能性,可能是因为这个问题来自2008年,但在2018年,你可以使用马特·戈德博尔特的在线网站https://godbolt.org

你也可以在本地克隆git并运行他的项目https://github.com/mattgodbolt/compiler-explorer

如果您希望看到的内容依赖于输出的链接,那么除了前面提到的gcc -S之外,输出对象文件/可执行文件上的objdump也可能有用。下面是Loren Merritt编写的一个非常有用的脚本,它将默认的objdump语法转换为更可读的NASM语法:

#!/usr/bin/perl -w
$ptr='(BYTE|WORD|DWORD|QWORD|XMMWORD) PTR ';
$reg='(?:[er]?(?:[abcd]x|[sd]i|[sb]p)|[abcd][hl]|r1?[0-589][dwb]?|mm[0-7]|xmm1?[0-9])';
open FH, '-|', '/usr/bin/objdump', '-w', '-M', 'intel', @ARGV or die;
$prev = "";
while(<FH>){
    if(/$ptr/o) {
        s/$ptr(\[[^\[\]]+\],$reg)/$2/o or
        s/($reg,)$ptr(\[[^\[\]]+\])/$1$3/o or
        s/$ptr/lc $1/oe;
    }
    if($prev =~ /\t(repz )?ret / and
       $_ =~ /\tnop |\txchg *ax,ax$/) {
       # drop this line
    } else {
       print $prev;
       $prev = $_;
    }
}
print $prev;
close FH;

我怀疑这也可以用在gcc -S的输出上。

这将生成C代码+行号交织的汇编代码,以便更容易地查看哪些行生成了什么代码(-S -fverbose-asm -g -O2):

# Create assembler code:
g++ -S -fverbose-asm -g -O2 test.cc -o test.s

# Create asm interlaced with source lines:
as -alhnd test.s > test.lst

在第3页(PDF的第15页)中找到了它。