个人认为,cmake可以在学习coding的这个过程中遇到不会的再去学习和总结记录!今天我又学到了在linux下,还有一种比较万能的通用CMakeLists.txt的写法:(用这篇博客记录一下)
(当然,如果你要在linux上引用什么thread类,还有别的库的源代码来用的时候,就肯定不止是这几条cmake代码这么简单了哈,到时候遇到了我再边用边学习即可了!)
废话不多说,直接上代码:
CMakeLists.txt:
cmake_minimum_required(VERSION X.X.X)
//指定Cmake的最低版本!在linux终端下可以用cmake --version 命令来查看你当前的cmake的版本!
project(Your_project_Name)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -Wall")
#指定该项目是可调试的和显示warning信息的
set(CMAKE_BUILD_TYPE Debug)
#指定调试时用debug来调试
file(GLOB SRC_FILES
"${PROJECT_SOURCE_DIR}/src/*.h"
"${PROJECT_SOURCE_DIR}/src/*.cpp"
"${PROJECT_SOURCE_DIR}/src/*.c"
"${PROJECT_SOURCE_DIR}/src/*.cc"
)
#自动帮你管理好src中的.h头文件还有.cpp 甚至还有.c .cc等的源文件!
add_executable(${CMAKE_PROJECT_NAME} main.cpp ${SRC_FILES})
#${CMAKE_PROJECT_NAME}就算自动帮你取你在第2个cmake命令下写的项目文件名字的意思
#${SRC_FILES}就是取我上面配置好了的src目录下的all源文件和头文件的意思!
demo代码:
//swap.h
#pragma once
void swap(int& a,int& b);
//swap.cpp
#include"swap.h"
void swap(int& a,int& b){
auto t = a;
a = b;
b = t;
}
//main.cpp
#include<iostream>
#include"src/swap.h"
using namespace std;
int main(void){
int a = 1,b = 2;
cout<<"a = "<<a<<",b = "<<b<<endl;
cout<<"after swap: "<<endl;
swap(a,b);
cout<<"a = "<<a<<",b = "<<b<<endl;
return 0;
}
运行结果:
但是最通用的还是以下这种CMakeLists.txt:
用include文件夹管理.h头文件,用.src文件夹管理.cpp源文件!这种方式才是最保险和通用的!
cmake_minimum_required(VERSION 3.0.0)
project(Your_project_Name)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -Wall")
set(CMAKE_BUILD_TYPE Debug)
include_directories(${CMAKE_SOURCE_DIR}/include)
file(GLOB SRC_FILES
"${PROJECT_SOURCE_DIR}/src/*.cpp"
)
add_executable(${CMAKE_PROJECT_NAME} main.cpp ${SRC_FILES})
demo codes:
//person.h
#pragma once
#include<iostream>
using namespace std;
class Person{
public:
int m_Age;
string m_Name;
Person(int age,string name):m_Age(age),m_Name(name){}
virtual void eat();
};
//person.cpp
#include"person.h"
void Person::eat(){
cout<<"Person "<<p.m_Name<<" is eating!"<<endl;
}
//student.h
#pragma once
#include<iostream>
#include"person.h"
using namespace std;
class Student : public Person{
public:
int m_Age;
string m_Name;
Student(int age,string name):Person(age,name){}
virtual void eat();
};
//student.cpp
#include"student.h"
void Student::eat(){
cout<<"Student "<<p.m_Name<<" is eating!"<<endl;
}
//main.cpp
#include<iostream>
#include"person.h"
#include"student.h"
using namespace std;
int main(void){
Person* pp = new Person(22,"lyf");
pp->eat();
Person* ps = new Student(23,"lzf");
ps->eat();
Student* s = new Student(23,"lzf");
s->eat();
return 0;
}
运行结果: