如何从 gcc 中的 C/C++ 源代码获取汇编程序输出?

2022-01-31 00:00:00 gcc debugging c assembly c++

如何做到这一点?

如果我想分析某些东西是如何编译的,我将如何获得发出的汇编代码?

If I want to analyze how something is getting compiled, how would I get the emitted assembly code?

推荐答案

使用 -S 选项来 gcc(或 g++).

Use the -S option to gcc (or g++).

gcc -S helloworld.c

这将在 helloworld.c 上运行预处理器 (cpp),执行初始编译,然后在运行汇编器之前停止.

This will run the preprocessor (cpp) over helloworld.c, perform the initial compilation and then stop before the assembler is run.

默认情况下,这将输出一个文件 helloworld.s.仍然可以使用 -o 选项设置输出文件.

By default this will output a file helloworld.s. The output file can be still be set by using the -o option.

gcc -S -o my_asm_output.s helloworld.c

当然,这只有在您有原始来源时才有效.如果您只有生成的目标文件,另一种方法是使用 objdump,通过设置 --disassemble 选项(或缩写为 -d形式).

Of course this only works if you have the original source. An alternative if you only have the resultant object file is to use objdump, by setting the --disassemble option (or -d for the abbreviated form).

objdump -S --disassemble helloworld > helloworld.dump

如果为目标文件启用了调试选项(编译时-g)并且该文件没有被剥离,则此选项效果最佳.

This option works best if debugging option is enabled for the object file (-g at compilation time) and the file hasn't been stripped.

运行 file helloworld 将为您提供一些关于使用 objdump 将获得的详细程度的指示.

Running file helloworld will give you some indication as to the level of detail that you will get by using objdump.

相关文章