Difference between compiling code and executing code

Viewed 114

So I write a program in some language, LanguageX, using a simple text pad.

Then I put that text into a Compiler. The compiler outputs machine code (or assembly which is then compiled into machine code)

My question is, who actually executes the compiled program.

Does the compiler execute it? Or do I need another "executor app" execute it? Or does the hardware execute the program directly? But who orders the hardware to do that?

I'm confused because the concepts of compiling a program, and executing a program, seem to be used interchangeably.

An example is HTML. I can write html code in a text file and save it as .html, open it with Firefox, and it will run. Is Firefox a compiler, an executor, both, neither?

Another example is a commercial app I buy and install. Whenever I click on the .exe, is the app compiled or executed? Both?

1 Answers

A program is data that explains how to execute things. You can read the program yourself and have a sense of what it should be doing, or give it to another program that can execute it. When a program is directly executed from its source, it is said to be "interpreted".

For example, your browser is interpreting HTML to render a page. When there is Javascript associated with a page, this is loaded and executed by a Javascript interpreter that has access to your page and its elements. The Javascript interpreter is part of your browser program, and your browser is a program that is executed by a processor.

A compiler is a program that transforms the source code into another language, typically instructions that can be decoded by your CPU, but that may be also bytes not directly executable by a processor, but by a virtual machine (another program that knows how to interpret the byte code).

For some languages the compilation phase also involves also a step called linking, but the resulting file is basically a bit of metadata and a sequence of instructions your processor can understand.

In order to execute a program, you ask (through a shell or the graphical interface) your operating systems to load the program: the kernel allocates resources for your process and put the code in a portion of memory that is flagged as executable (there are a lot more details to it).

The kernel keeps track of processes and executes them in one or more processors. The code is being fed directly to a processor which can decode the instructions resulting from compilation. Periodically, a process is interrupted by the kernel to let other processes run (when the process is waiting for something, or due to something called an "interrupt"). When you have multiple processors, multiple programs can execute truly in parallel.

See for example Linux Kernel Teaching for a lot more details.

Related