Chapter 2 basics-5th. Build C ++ programs

Source: Internet
Author: User
Vernacular C ++ [back to the Directory]

. Build a C ++ Program

C ++ is a typical "compiled" language.

For compiled languages, we can refer to the process of "code into a program" as "Compilation" in general ". However, if subdivided, this process also includes the following three sub-processes:

  • Precompiled/precompile
  • Compile/compile
  • Link

In this case, to avoid confusion, we need to turn the complete process of "code into a program", called "build/build ". The sub-process above can be further refined, but it is enough to understand this three-way step for common programming.

5.2.1. Pre-compile

"
Pre-compilation is also called "preprocessing/preprocessing". It is like a cooking master needs to wash and cut the dishes before cooking. The remaining condiments must be prepared and placed in
The location that is readily available. Before compiling a program, the compiler needs to read the source code to be compiled, sort the format in the memory, and convert part of the content to facilitate subsequent content.

For example, C ++ is used to perform the logical "or" operation with the symbol "|", but the computer keyboard in some countries lacks the character "|, c ++ can also use the word "or" to indicate this operator. During pre-compilation, these replacement symbols can be mapped to a unified code in the memory.

The more common content is that C ++ allows some "pre-compilation instructions" to temporarily invalidate some code in a certain compiling environment (you do not need to compile it). These invalid codes, during pre-compilation, you can clear the content in the memory, such

001 // use the macro definition to check whether the current compilation is in the Windows operating system
002 # ifdef _ Win32 __
003 STD: String OS = "Windows ";
004 # End

If the above Code is compiled in the Linux operating system, the 003 lines of code will be removed. The comments are also cleared, for example, 001 lines of code.


Tip: Can macro detect the current operating system?

A macro is only composed of several characters. It does not have such magical power to check the current operating system. In fact, it is a person (programmer) Who predefines some macros based on the current compiling environment.

 

However, the most important part in the pre-compilation process is the macro replacement in C/C ++ ". The so-called "macro" means that C/C ++ allows a (usually short, meaningful) identifier to represent another one-to-one segment (usually lengthy, or meaningless) code, such:

# Define Pai 3.14159265

This Code uses the symbol "Pai", representing a long cycle rate of "3.14159265 ". In pre-compilation, unless the macro definition code is canceled, the "Pai" flag will be replaced with the specific 3.14159265 value. For example

Int radius; // radius
Cout <"Enter the radius :";
Cin> radius;
Double circumference = 2 * PAI * radius;
Cout <"Perimeter =" <circumference <Endl;

After pre-compilation, convert

Int radius;
Cout <"Enter the radius :";
Cin> radius;
Double circumference = 2*3.14159265 * radius;
Cout <"Perimeter =" <circumference <Endl;

5.2.2. Compile

The C ++ code is converted into a machine language, which is completed during the compilation phase. Any syntax errors in our program will be found by the compiler. Some code that is syntactically correct, but which the compiler considers as "suspicious", will also be raised in the form of a "warning.

For beginners, it usually takes 10 minutes to write the code, but it takes 120 minutes to solve the problem given by the compiler.

In such an important stage, maybe we should use a lot of space to describe it? This is another course. If you are interested, please purchase relevant books for reading.


Classroom assignment: Observe compilation error messages

Use code: blocks to open the "Hello World" classic edition project and comment out the 4th lines of code. The effect is as follows:

// Using namespace STD;

Recompile the project, observe that the compiler gives a message, and understand it. Note that the "error" and "warning" types are distinguished.

 

The answer to this assignment is as follows:

Compilation Information and Related explanations (to save space, the file path information is omitted ):

| = Helloworld, DEBUG = |

.../Main. cpp | in function 'int main () ': |

(Main function in the main. cpp file :)

.../Main. cpp | 8 | error: 'cout' was not declared in this scope |

(Row 8th of Main. cpp, error: 'cout' is in the current range and its declaration cannot be found)

.../Main. cpp | 8 | error: 'endl' was not declared in this scope |.../Main. cpp | 8 | warning: unused variable 'cout' |

(Row 8th of Main. cpp. Warning: cout is not used)

.../Main. cpp | 8 | warning: unused variable 'endl' |

(Line 3 of Main. cpp, warning: Endl is not used)

| |=== Built: 2 errors, 2 warnings ==|

The compiler first reports an error saying "'cout' is in the current range and cannot find its Declaration ". Cout is declared in the namespace STD, but we just commented out the use of the namespace, so the compiler will not find the cout declaration.

Then, since the compiler cannot find the cout and declaration, it will try to dress and pretend to be confused and treat cout as a variable. As a result, it feels wrong, this cout variable was not used (correctly), so it again reported a warning.

There is a problem with compilation. Read the compilation message carefully and compare it with the actual code ...... Head shot: "Oh! It turned out to be ......" Quickly modify the code and then try to compile ...... Passed! Really happy; still wrong, really worried-this is the programmer's daily life.


[Important]: Important Notes on compilation Information

1. warning messages are equally important. We have learned this before.

2. the compiler is not "God", so the row number it prompts is sometimes very accurate, but sometimes not at all, how to accurately locate the error location, it depends on your familiarity with the c ++ language and your experience.

3. After compilation is passed, it only indicates that the syntax is correct, not that this is a correct program.

 

5.2.3. Link

When talking about the link, I am confused: "I have already compiled it into a machine language. Isn't it all done? What is the link ?"

Originally, the C ++ compilation process was performed by a single source file. Suppose you have a project named K to write a program. It contains two source files: A. cpp and B. cpp. The compilation process will be:

First, pre-compile a. cpp, compile a. cpp, and generate the target file: A. O;

2. Pre-compile B. cpp, compile B. cpp, and generate the target file: C. O;

3. Link A. O and C. O and the executable file k.exe appears.

The "target" file is also intuitively called an "intermediate file" because it can be deleted after being linked to an executable file.


Tip: Extension of the target file and Executable File

The extension name of the target file and executable file depends on the operating system or compiler. .objand .exe are the default style in the Windows operating system. However, for the G ++ compiler under mingw32, the generated target file extension is ". O ".

 

In this way, one of the main tasks of "Link" becomes easy to understand: during compilation, each source file is compiled into a machine language, but it is a scattered multiple target files, as a result, the linker "concatenates" or "assembles" these target files into a complete executable file.


「 Easy moments 」: What are the greatest fears of "splicing?

When I was a child, I was a "Demolition crazy". My father's bedside alarm clock was installed after the split. However, after the first split, I added several parts, I lost a few parts for the second time, and finally the alarm clock was tossed to death.

Now I am also a father. When I was two years old, I like to play with my laptop. When I was three years old, I found her keyboard in her notebook, and I was shocked, I immediately went home to the toy market and bought several sets of jigsaw puzzle games.

 

Speaking of this, the compiler is a very "Babu" guy who often picks out a lot of errors in the code without considering our faces. The linker is much more cool than it. Its favorite mistake is that there are only two: one is: "XXX missing" and the other is "XXX more ". Here, "XXX" is not a source file, but an object in the Code. The most common is a function.

Continue to the example where K project contains a. cpp and B. cpp. Suppose we use a function named "Foo ()" in A. cpp ()". The compiler does not require us to immediately find the implementation of this function. On the contrary, we only need to give the "Declaration" of this function. The so-called "declaration" is to tell the compiler what the "function looks like ".

Who is responsible for finding the true body of the "Foo ()" function? The "linker" is also. The linker found. the "Foo ()" function is used in O, so it is first used in. o. I checked it and couldn't find it. So I went to B. sorry, I couldn't find it again. Now it's in a hurry, so I complained, "A FOO () is missing ()! ".

I understood this "XXX is missing" and the "XXX is missing" error is easy to understand. Imagine. O found "Foo ()", is proud, but when the Assembly is complete, found in B. there is an identical "Foo ()" In O, and it will be called out: "Wow, there is actually one more Foo ()!"

Let's modify the "Hello World" classic edition Code as follows:

/* This is my first C ++ Program */
# Include <iostream>

004 using namespace STD;

006 void Foo ();

Int main ()
{
010 Foo ();

Cout <"Hello world! "<Endl;
Return 0;
}

Row 004. Remember to remove the comments from the previous section.

Row 006, we declare a "Foo ()" function.

Line 10: We have called this non-actually "Foo ()" function.

A link error occurs when you recompile the project. Switch to the "build record" page in the message bar (Press f2 to ensure display). We first view the following information in the record:

-------------- Build: Debug in helloworld ---------------

Compiling: Main. cpp

Link to the console to execute: Bin/debug/helloworld.exe

The information shows that the "Compilation" process has been completed, and the problem lies in the "Link" process. Switch the message bar to "build information" and see the following error message:

OBJ/debug/Main. o | in function 'main': |

.../Main. cpp | 10 | undefined reference to 'foo () '|

| |=== Built: 1 error, 0 warnings ==|

This time, the problem occurs from "OBJ/debug/Main. O". Of course, the linker also worked very hard to remind us that the 10th line of Main. cpp may be a problem.

 

[Back To Directory]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.