单独编译:
通常我们可以把程序分成三部分:
1.头文件:包含结构声明和使用这些结构的函数的原型;
2.源代码文件:包含于结构有关的函数的代码;
3.源代码文件:包含调用与结构相关的函数的代码.
在UNIX系统中编译由多个文件组成的C++程序, 的示意图
从示意图中可以看出最终会将多个文件编译成一个可执行文件
通常头文件中包含以下内容:
1.函数原型
2.使用#define或const定义的符号常量
3.结构声明
4.类声明
5.模板声明
6.内联函数
如果文件名包含在尖括号中, 则C++编译器将在存储标准头文件的主机系统的文件系统中查找. 如果文件名包含在双引号中, 则编译器首先查找当前的工作目录或源代码目录, 如果没有在哪里找到头文件, 则将在标准位置查找. 因此在包含自己的头文件时, 应使用引号而不是尖括号.
来看一个简单的由多个文件共同编译成一个可执行文件的例子:
头文件 coordin.h, 主要定义了需要使用的结构体, 和函数原型
// corrdin.h
// 结构原型
#ifndef COORDIN_H_
#define COORDIN_H_
struct polar
{
double distance;
double angle;
};
struct rect
{
double x;
double y;
};
// 函数原型
polar rect_to_polar(rect xypos);
void show_polar(polar dapos);
#endif
在同一个文件中只能将同一个头文件包含一次, 但是我们很容易由于某些原因包含多次, 例如使用包含了另外一个头文件的头文件. 因此C/C++有一种方式来避免多次包含头一个头文件. 它是基于预处理编译指令#ifndef(if not defined)的, 下面的代码意味着当且仅当以前没有使用预处理器编译指令#define定义的名称COORDIN_H_时, 才处理#ifndef和#endif之间的语句:
#ifndef COORDIN_H_
...
#endif
通常使用#define语句来创建符号常量, 例如:
#define MAXIMUM 4096
但是只要将#define用于名称, 就足以完成该名称的定义.
#define COORDIN_H_
file1.cpp , 里面主要定义了需要使用的函数
// file1.cpp 包含了在file1.cpp中的需要使用的函数的定义
#include <iostream>
#include <cmath>
// 结构体原型, 函数原型
#include "coordin.h"
using namespace std;
polar rect_to_polar(rect xypos)
{
polar answer;
answer.distance = sqrt(xypos.x * xypos.x + xypos.y * xypos.y);
answer.angle = atan2(xypos.y, xypos.x);
return answer;
}
void show_polar(polar dapos)
{
const double Rad_to_deg = 57.296;
cout << "distance = " << dapos.distance;
cout << ", angle = " << dapos.angle * Rad_to_deg;
cout << " degrees" << endl;
}
file2.cpp , 主要是main函数, 也就是主体逻辑
// file2.cpp
#include <iostream>
// .h文件中包含了结构体原型, 和函数原型
#include "coordin.h"
using namespace std;
int main()
{
rect rplace;
polar pplace;
cout << "Enter the x and y values: ";
while(cin >> rplace.x >> rplace.y)
{
pplace = rect_to_polar(rplace);
show_polar(pplace);
cout << "Next two numbers(q to quit) : ";
}
cout << "Bye !" << endl;
return 0;
}
蓝看一下运行结果:
编译的是后需要列出所要编译的文件 -o 后面写编译出的可执行文件的名字