作用:代码结构更清晰
步骤
- 创建后缀名为.h头文件
- 创建后缀名为.cpp源文件与main.cpp源文件
- 头文件编写函数声明
- 源文件编写函数定义
项目结构
IDE:Clion
示例
第一步:编写test.h文件
#include <iostream>
using namespace std;
//函数声明
int add(int num1, int num2);
第二步:编写test.cpp文件
#include "../Headers/test.h"
int add(int num1, int num2) {
return num1 + num2;
}
第二步:编写main.cpp文件
#include "test.cpp"
int main() {
//调用add()函数
cout<<add(2,5)<<endl;
}
解决方案(若运行报错)
解决方案:
第一步: 点击File–>Settings
第二步: 点击Plugins,搜索C/C++ Single File Execution,点击install
第三步:点击Restart,重启Clion
第四步,删除之前的所有.cpp文件,重新新建
注意:取消勾选Add to targets
第五步:main.cpp文件右键,选择 “Add executable for single c/cpp file”
第六步: 在CMakeLists.txt中,若点击Auto-Reload,下次选择 “Add executable for single c/cpp file”时,自动配置;若点击Reload changes,每次都需自己在此文件配置。
最后,选中main(上面第五六步配置进来的),再点击运行