理解Compiling and Linking in C++

  • 前言

    The compilation is the process which convert the program written in human readable language like C, C++ etc into a machine code, directly understood by the Central Processing Unit.

    There are many stages involved in creating a executable file from the source file. The stages include:

    • Preprocessing
    • Compiling
    • Linking

    This means that even if the program gets compiled, it may result in not running as errors may arise during the linking phase.

  • Preprocessing

    In this pahse the preprocessor changes the Preprocessing program according to the directives mentioned (that starts with # sign).

    The C++ preprocessor takes the program and deals with the # include directives and the resulting program is pure c++ program.

    For example, in c++ program #include<iostream> will tell the preprocessor to read all the contents of the iostream header file and include the contents into the program and generate the separate C++ program file.

    c++ supports many preprocessor directives like #include, #define, #if , #else etc.

  • Compilation

    This phase translates the program into a low level assembly level code.

    The compiler takes the preprocessed file (without any directives) and generates an object file containing assembly level code. The object file created is in the binary form.

    In the object file created, each line deacribes one low level machine level instruction.

    The conversion to assembly language is important as it is common output language for many compilers high-level languages.

    扫描二维码关注公众号,回复: 11581595 查看本文章
  • Assembly

    There is also assembly phase which converts these object files in assmbly code into machine level instructions and the file created is a relocatable object code.

    Hence, the compilation phase generates the relocatable object program and this program can be used in different places without have to compile again.

    But you still can’t run these object files until to convert them into executable file, now here linker comes into play, which links all the object files to generate single executable file.

  • Linking

    Linking as the name suggests, refers to creation of a single execuable file from multiple object files.

    The file created after linking is ready to be loaded into memory and executed by the system.

    There is difference in linking and compilation when it comes to understanding errors. Compiler shows errors in syntax, for example semi-colon not mentioned, data type not defined etc but if there is an error that function has been defined multiple times, then this error is from linker as its indicating that two or more source code files have the same meaning and that is leading to an error.

  • References

  1. cplusplus.com
  2. How does the compilation/linking process work?
  3. COMPILER, ASSEMBLER, LINKER AND LOADER : A BRIEF STORY

猜你喜欢

转载自blog.csdn.net/The_Time_Runner/article/details/107290550