1
$\begingroup$

I am learning about and building a very basic compiler. My question is about code generation. I have read on a lot of materials about code generation when building a compiler and I get the concept.

Suppose I am targeting only a single architecture and OS, for a very basic language, and I have completed all the necessary steps and generated the assembly code for that specific architecture and OS. How would I do such that this assembly code gets compiled to an executable file from my compiler alone such that invoking it like: my_compiler codefile.mylangugage produces an executable file, instead of first compiling to assembly then having the user to call an assembler such as nasm themselves?

As an addition, if you can also tell how interpreted languages and virtual machines convert to machine code (just the overview)?

$\endgroup$

1 Answer 1

2
$\begingroup$

Assembly language is basically meant to be a 1:1 representation of the underlying CPU machine code. (Yes I'm aware there are a few exceptions, especially with modern assemblers) The difference is you are representing actual machine opcodes with short "mnemonic codes" that make it slightly easier to understand what is happening. So Opcode FF in hex might become JMP in assembler, which refers to an instruction to jump to a particular memory address.

Honestly, if you can write a compiler that generates assembly language, how are you not aware of this and how can you not simply write a compiler that generates the machine code directly?

$\endgroup$
2
  • $\begingroup$ I will be writing one, so I was just planning ahead. Would generating the machine code be done by invoking the assembler from the compiler I write? $\endgroup$
    – Ali Ahmed
    Feb 21 at 11:05
  • $\begingroup$ You are talking a simple language and a single architecture, so I assume we're talking something basic. So this is an old-school answer based on simple old-school architectures. In those cases, assembly and machine code had a 1:1 correspondence. So if you just want to generate machine code directly, simply translate your code into the machine code numerical op-codes instead of the assembly mnemonics. Now, as far as the OS, you need to know what is involved in making that file an executable. What headers does it need, what file extension, etc. $\endgroup$ Feb 21 at 18:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.