我们可以自己写一个头文件,然后把部分代码放进去。
比如一个随机数生成函数
我们可以将里面的部分放到一个叫random.h的头文件中:
#ifndef _RANDOM_H
#define _RANDOM_H
/***原来的部分代码******/
#include<time.h>
#include<stdlib.h>
#define RANDOM(start,end) start + rand() % (end - start + 1)
#define SRAND srand((unsigned int)time(NULL))
int random(int start, int end) {
static bool first = true;
if (first) {
srand((unsigned int)time(NULL));
first = false;
}
return start + rand() % (end - start + 1);
}
/*******************************/
#endif
头文件的代码需要用
#ifndef name//如果此名称没有定义
#define name//那就定义此名称
你的代码
#endif//结束
我们知道预处理器会将#include的内容粘贴到源文件中,为了防止同一段程序被引用多次造成错误,一般都用这种格式包裹头文件,预处理器会检查名称,如果是已经include过的,那么不会再include一次。
这个名称可以随便起,只要不重复。一般的,大家都会用头文件名的大写形式来作为#define的内容。
然后,我们将剩下的主函数放在main.cpp中,并且将头文件包含进来。
#include<iostream>
#include"random.h"
using namespace std;
int main() {
//函数法
for (int j = 0;j < 10;j++)
cout << random(5, 20) << ' ';
cout << endl;
//宏法
SRAND;
for (int j = 0;j < 10;j++)
cout << RANDOM(5, 20) << ' ';
cout << endl;
}
编译,运行,和原来一个文件时一样。
还有一种更规范的方法,就是在头文件中只写函数声明,将定义部分放在cpp文件中。
比如,我们将random()的定义放在rd.cpp中,剩余部分放在rd.h中,并加上一句random()的声明。
首先是rd.h
#ifndef _RD_H
#define _RD_H
#include<time.h>
#include<stdlib.h>
#define RANDOM(start,end) start + rand() % (end - start + 1)
#define SRAND srand((unsigned int)time(NULL))
int random(int start, int end);
#endif
然后,rd.cpp
#include"rd.h"
int random(int start, int end) {
static bool first = true;
if (first) {
srand((unsigned int)time(NULL));
first = false;
}
return start + rand() % (end - start + 1);
}
注意,cpp文件要include头文件
然后main.cpp依旧只保留主函数和#include"rd.h"
#include<iostream>
#include"rd.h"
using namespace std;
int main() {
//函数法
for (int j = 0;j < 10;j++)
cout << random(5, 20) << ' ';
cout << endl;
//宏法
SRAND;
for (int j = 0;j < 10;j++)
cout << RANDOM(5, 20) << ' ';
cout << endl;
getchar();
}
此时,如果你如果在用VS,那么可以直接编译运行,如果你用的是VS code,那么在终端输入以下g++命令。
//编译main.cpp和rd.cpp
g++ -c main.cpp -o main.o
g++ -c rd.cpp -o rd.o
//链接二者,生成名为main的可执行文件
g++ rd.o main.o -o main
以上,就是自己建头文件并编译的方法。