CPP函数分文件编写
下面以swap函数为例讲一下在clion中如何分文件编写函数并编译运行
- 创建头文件,这里创建了
swap.h
头文件
#ifndef SWAP_H
#define SWAP_H
#include <iostream>
using namespace std;
void swap(int &a,int &b);
#endif //SWAP_H
- 创建函数文件,这里创建了
swap.cpp
文件
#include "swap.h"
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
- 调用函数,这里创建了
swap_using.cpp
#include "swap.h"
int main(){
int a = 5;
int b = 10;
cout << "Before swapping: a = " << a << " b = " << b << endl;
swap(a, b);
cout << "After swapping: a = " << a << " b = " << b << endl;
return 0;
}
- 编写
CMakeList.txt
文件,在其中添加add_executable(swap swap.cpp swap_using.cpp)
命令,示例如下
cmake_minimum_required(VERSION 3.28)
project(demo)
set(CMAKE_CXX_STANDARD 17)
add_executable(main main.cpp) # 别的文件编译
# 编译多个文件
add_executable(swap swap.cpp swap_using.cpp)