//C++ example in C++11#include#include#includeusingnamespace std;intmain(){
vector<string> msg {"Hello","C++","World","!"};for(const string& word : msg){
cout << word <<" ";}
cout << endl;return0;}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Compile and run the program
Compile hello.cpp
g++ hello.cpp
1
Initialization of msg is a C++11 extension. We need
g++ hello.cpp --std=c++11
1
Executable file can be generates as a.out. Change the output filename by -o option
Development languages of most fundamental systems:
linux
MySQL
OpenCV
High Effiiency
Widely optimized compilers
Access memory directly
Excellent on computing
3-Complie and Link
Example
#includeusingnamespace std;intmul(int a,int b){return a * b;}intmain(){int a =0, b =0;int result =0;
cout <<"Pick two integers:";
cin >> a;
cin >> b;
result =mul(a, b);
cout <<"The result is "<< result << endl;return0;}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Function prototypes and definitions
function prototypes are put into head files (*.hpp)
intmul(int a,int b);
1
function definitions normally are in source files (*.c, *.cpp)
intmul(int a,int b){return a * b;}
1
2
3
4
Separate the source codes into multiples files
#main.cpp#include#include"mul.hpp"usingnamespace std;intmain(){int a =0, b =0;int result =0;
cout <<"Pick two integers:";
cin >> a;
cin >> b;
result =mul(a, b);
cout <<"The result is "<< result << endl;return0;}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#mul.cpp#include"mul.hpp"intmul(int a,int b){int c = a / b;return c * b * b;}
1
2
3
4
5
6
7
8
9
#mul.hpp#pragmaonceintmul(int a,int b);
1
2
3
4
5
Compile and link
g++ -c main.cpp. // -c 只编译不链接
1
g++ main.o mul.o -o mul // 两个文件并起来
1
Compilation errors
Normally caused by grammar
Please check the source code
Link errors
Symbol not found
Function mul() is misspelled to Mul()
Runtime errors
The source code can be successfully complied and linked
The floating point exception (divided by 0) will kill the program.
It is a typical runtime error.
Preprocessor and Macros
Preprocessor
The preprocessor is executed before the compilation.