1、编写.h头文件
首先为了防止重复编译,一般在头文件中加入“ #ifndef XXX #define XXX 。。。#endif"这样的语句。其中“ifndef”是指“if not define”,而“XXX”是自定义的名字,一般是.h文件名的大写形式。然后在上面语句的中间一般写类的声明(包括类里面的成员和方法的声明)、函数原型、#define常数等,但一般来说不写出具体的实现。编写一个名为“printhello.h”的头文件示例:
#ifndef PRINTHELLO_H_
#define PRINTHELLO_H_
void printhello();
#endif
2、编写函数具体实现的.cpp文件
#include <iostream>
void printhello(){
std::cout << "Hello!\n";
}
3、创建一个main.cpp进行测试
调用刚刚创建的头文件,用“”(标准库的用<>),然后使用头文件里面的函数printhello():
#include "printhello.h"
int main(int argc, char** argv) {
printhello();
return 0;
}