总体步骤:
-
创建后缀名为.h的头文件
-
创建后缀名为.cpp的源文件
-
在头文件中写函数的声明
-
在源文件中写函数的定义
1.创建后缀名为.h的头文件
项目的头文件中添加一个新建项,然后创建一个.h文件
2.创建后缀名为.cpp的源文件
在源文件夹下创建swap.cpp
//这里需要包含头文件
#include"swap.h"
3.在头文件中写声明
//因为swap.cpp中用到cout,所以必须包含这两个部分
#include<iostream>
using namespace std;
//函数声明
void swap(int num1, int num2);
4.在源文件中写函数定义
//这里需要包含头文件
#include"swap.h"
void swap(int num1, int num2)
{
int temp = num1;
num1 = num2;
num2 = temp;
cout << "num1 = " << num1 << endl;
cout << "num1 = " << num2 << endl;
}
测试一下是否成功!
#include<iostream>
using namespace std;
//双引号表示自己编写的文件
#include"swap.h"
/*
1.创建后缀名为.h的头文件
2.创建后缀名为.cpp的源文件
3.在头文件中写函数的声明
4.在源文件中写函数的定义
*/
int main()
{
int a = 2;
int b = 4;
swap(2, 4);
system("pause");
return 0;
}