Will C++ first gets converted to assembly [duplicate]

吃可爱长大的小学妹 提交于 2020-08-05 10:18:10

问题


I have confusion. I am C++ developer and heard many times that my source code will first gets converted to assembly and then assembly will get converted to machine code. But in one of the video tutorial of assembly language, instructor clearly said, C/C++ code directly gets convert to machine code. (Of course there will be linking and loading there).

I have seen links like this, Does the C++ code compile to assembly codes?

Still I am not able to clarify my doubt.

If in case, C++ does not gets converted to assembly first, how de-assembler generate assembly code from binary.


回答1:


In the old (very old) days, compilers worked like this:

  1. The compiler generated assembly code in a file and wrote it to disk,
  2. The assembler took that file and generated the binary.

These days, unless you really want assembly output, your compiler does not generate explicit assembly language code. It will just generate some assembly in memory but then convert it to machine code themselves and only write the machine code to file. This is what your instructor meant when saying that C/C++ gets directly converted to machine code.

There is one more important thing you should know. Machine code is basically the same thing as assembly language. In assembly languages, instructions have names and written using strings, but these are the same instructions (one-to-one mapping) that are used in machine code. This is important so I repeat myself: machine code and and assembly are the same, only written in different notations.

This is why any binary can be disassembled; because to convert something from machine code to assembly, you just have to change the representation (translate each instruction and its operands from binary to "mnemonic" form.

So, modern compilers may actually not generate the actual strings that represents instructions (e.g. mov rax, 42) for performance reasons. If nobody wants the assembly output, why waste the memory and processing power generating it? But of course they do generate the equivalent machine code, which is faster for a compiler to generate.




回答2:


As machine code maps to assembly quite directly, there it is not very practical to analyze the difference. As C++ language stands it only describes behavior, and up to the implementation what it does. It is possible to emit CLI code or java bytecode or whatever too.

In practice most implementations really go all the way and emit assembly/machine level optimized code at the end. And support emission of assembly source file (.asm, .s) or annotated code/assy/C++ source.



来源:https://stackoverflow.com/questions/17196113/will-c-first-gets-converted-to-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!