如何做到这一点呢?
如果我想分析某些东西是如何编译的,我该如何获得发出的程序集代码?
如何做到这一点呢?
如果我想分析某些东西是如何编译的,我该如何获得发出的程序集代码?
当前回答
如果您希望看到的内容依赖于输出的链接,那么除了前面提到的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的输出上。
其他回答
使用-S开关:
g++ -S main.cpp
或者也可以用gcc:
gcc -S main.c
还有这个。
从FAQ如何让GCC生成汇编代码:
gcc -c -g -Wa,-a,-ad[其他gcc选项]foo.c > foo.lst
作为philrephly的答案的替代方案。
或者像大家说的,用-S。
下面是在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选项。我还想补充一点,根据是否添加优化选项(-O0表示没有,-O2表示积极优化),结果可能会有所不同(很大程度上!)
特别是在RISC架构上,编译器在进行优化时经常会把代码转换得几乎认不出来。结果令人印象深刻,令人着迷!