Search code examples
compilation

when does the compiler compile the code into machine code?


As far as I know, the compiler compiles the code by converting it to a language that a computer can understand which is the machine language and this is done before running the code.

So, does the compiler compile my code each time I write a character in the file?

And if so, does it check the whole code? Or just the line that updated.


Solution

  • An important part to this question is the type of programming language(PL) we are talking about. Generally speaking, I would categorize PL into 3 groups:

    Traditional PLs. Ex: C, C++, Rust

    The compiler compiles the code into machine language when you hit the "build" button or the "run" button. It doesn't compile every time you change the code, but a code linter does continuously observe your code and check it for errors.

    Another note, when you change part of the code and compile it, the compiler doesn't recompile everything. It usually only recompile the current assembly file (or module or whatever you call them).

    It is also important to note that a lot of modern IDEs, compile when you save the files.

    There is also the hot reload feature. It is a smart compiler feature that can swap certain parts of the code while it is running.

    Interpreted PLs Ex: python, JS and PHP

    Those languages never get compiled; Rather, they get interpreted or translated into native code on the fly and in-memory when you run them. Those languages usually employee a cache to accelerate the subsequent code execution.

    Intermediary Code PL. Ex: Kotlin, java, C#

    Have 2 stages of compilation:

    • Build time compilation.
    • Just in time (run-time) compilation.

    Build time compilation converts the code into intermediary language (IL) machine code, which is special to the run-time. This code only understood by the run time like Java runtime or dot net runtime

    The second compilation happens when the programs get installed or ran for the first time. This is called just in time compilation (JIT)

    The run-time convert the code into native code specific to the run-time OS.