This article explains how to get c++ code corresponding to assembly code, to really understand how a piece of code is executed, or from the assembly level, that how to get a piece of c++ code corresponding to assembly code, here are three ways for you to introduce.

1. GCC compiles the xxx. s file

In general, if you give a CPP file such as test. CPP, then we will compile it directly with g++ test. CPP, but there are many processes in it, including preprocessing, compiling, linking, and so on, and the compilation process is actually the generation of assembly file.

For example, for a CPP file, we execute the following command:

G++ -e test. CPP -o test. I # preprocessing process g++ -s test. I -o test. S # compilation processCopy the code

CPP = g++ -s test. CPP -o test.s

2. Run the objdump command to obtain assembly code

The objdump command on Linux is used to display certain information from an executable or object file, so it can also be used to obtain the assembly code corresponding to the executable file.

For example, for test. CPP, you can use the following command to get the assembly instruction:

g++ test.cpp -o test
objdump -d test
Copy the code

In this way you can see the executable file corresponding to the assembly instructions.

3. Use the GDB command to obtain assembly code

In the first and second cases, the assembly instructions are generated during compilation. However, because some code can only be determined at runtime, the assembly instructions at runtime are not exactly the same as those at compile time. For example, the address of the stack is not known at compile time, so the runtime will actually allocate it.

We can use GDB to get the assembly instructions for each line of code at run time, first using g++ -g test. CPP -o test to get the executable file, then GDB./test to go into GDB mode, for example for this c++ code:

#include <iostream>
using namespace std;

int main(a)
{
	int size = 1000;
	size = 10000;
	int arr[size];

	return 0;
}
Copy the code

The corresponding assembly instruction can be obtained by using the following GDB command:

(gdb) b main Breakpoint 1 at 0x4006a4: CPP, line 10. (GDB) set disassemble-next-line on R Starting program: /root/a.out Breakpoint 1, main () at test.cpp:10 10 return 0; => 0x00000000004006a4 <main()+8>: 48 89 e0 mov %rsp,%rax 0x00000000004006a7 <main()+11>: 48 89 c1 mov %rax,%rcx (gdb) next 6 int size = 1000; => 0x00000000004006aa <main()+14>: c7 45 fc e8 03 00 00 movl $0x3e8,-0x4(%rbp) (gdb) 7 size = 10000; => 0x00000000004006b1 <main()+21>: c7 45 fc 10 27 00 00 movl $0x2710,-0x4(%rbp)Copy the code

We can see what the assembly instructions are for each line of c++ code, which is the most convenient method for beginners.

Well, this article is for you to introduce here, if you think the content is useful, remember to click a like oh ~