Piero Borrelli
Piero Borrelli

Reputation: 1221

Understand how the compiler works

I'm studying the C++ programming language and I have a questions about the how the compiler create an executable file. My book says:

C++ is a compiled language so you need to translate the source code in a file that the computer can execute. This file is generated by the compiler and it's called the object code ( .obj ), but a program like the hello world program is composed by a part that we written and part of the C++ library.

Which is this part in the hello world program?

Then my book says:

You must compile and link the two parts of the program to produce an executable file.

Does this mean that the executable file is the result of linking the two parts of the program and that the object code can't be executed?

Upvotes: 2

Views: 1045

Answers (3)

Tim Shen
Tim Shen

Reputation: 206

The two parts are 1) "your code that calls the print function and passes the string in", which is your compiled hello world program; 2) the code that implements the print function (say "std::cout <<"). We call it standard library.

Obviously, without the standard library object file, you can't get a complete executable because of lack of std::cout's implementation.

One of the reason that there is a standard library is to make the user code (your hello world file) more portable across different operating systems, because in Unix systems you actually have to use "write" function to print a string; but in other systems you may use functions other than "write". Standard library unifies it for you.

Details about standard library object file include techniques like template instantiation, which you may be not interested in for now.

Upvotes: 1

jpo38
jpo38

Reputation: 21514

C and C++ have to be compiled. You'll use a compiler that will translate your code into platform-specific executable.

Compiler does many steps:

  • The code is first pre-processed (replacing macros (#define) by their value and include files (#include) by their content.
  • Syntax analysis to check C++ syntax is valid
  • Sematic analysis to construct a tree of instructions
  • Optimization (if requested)
  • Code generation: it writes assembly code specific to the target platform
  • Linking: putting together all code into an executable program

At leats, that's what I remember from what I learn at school....

Upvotes: 1

duffymo
duffymo

Reputation: 308733

That's right: C and C++ both have separate compilation and link steps. The source is compiled to object code for that specific processor. The object files and libraries are linked together and then executed.

Java and C# both use byte code that is interpreted and executed by their respective virtual machines.

Upvotes: 0

Related Questions