案例二:同目录多文件
1). 源文件结构
.
├── CmakeLists.txt
├── main.cpp
├── student_pub.cpp
└── student_pub.h
- .编写 CMakeLists.txt
#cmake mini ~ver
cmake_minimum_required(VERSION 2.8)
#project info
project(Studdent2)
#target exe
**add_executable(Studdent main.cpp student_pub.cpp)** #单个文件添加
唯一的改动只是在 add_executable 命令中增加了一个 MathFunctions.cc 源文件。这样写当然没什么问题,但是如果源文件很多,把所有源文件的名字都加进去将是一件烦人的工作。更省事的方法是使用 aux_source_directory 命令,该命令会查找指定目录下的所有源文件,然后将结果存进指定变量名。其语法如下:
aux_source_directory(
源文件可以修改为:
#cmake mini ~ver
cmake_minimum_required(VERSION 2.8)
#project info
project(Studdent2)
#将当前路径下的源文件保存到变量DIR_SRCS中
aux_source_directory(. DIR_SRCS)
add_executable(Student ${DIR_SRCS}) #路径下文件添加
这样,CMake 会将当前目录所有源文件的文件名赋值给变量 DIR_SRCS ,再指示变量 DIR_SRCS 中的源文件需要编译成一个名称为 Student 的可执行文件。
3).cmake接口
aux_source_directory(. DIR_SRCS)
aux_source_directory 查找在某个路径下的所有源文件。
搜集所有在指定路径下的源文件的文件名,将输出结果列表储存在指定的变量中。该命令主要用在那些使用显式模板实例化的工程上。模板实例化文件可以存储在Templates子目录下,然后可以使用这条命令自动收集起来;这样可以避免手工罗列所有的实例。
使用该命令来避免为一个库或可执行目标写源文件的清单,是非常具有吸引力的。
但是如果该命令貌似可以发挥作用,那么CMake就不需要生成一个感知新的源文件何时被加进来的构建系统了(也就是说,新文件的加入,并不会导致CMakeLists.txt过时,从而不能引起CMake重新运行)。
正常情况下,生成的构建系统能够感知它何时需要重新运行CMake,因为需要修改CMakeLists.txt来引入一个新的源文件。当源文件仅仅是加到了该路径下,但是没有修改这个CMakeLists.txt文件,使用者只能手动重新运行CMake来产生一个包含这个新文件的构建系统。
案例二源文件
student_pub.cpp
#include<iostream>
#include<string>
#include"student_pub.h"
using namespace std;
void Student::display()
{
cout << "num : " << num <<endl;
cout << "name : " << name <<endl;
cout << "sex : " << sex <<endl;
}
Student::Student():num(11),name("meng11"),sex('M')
{
// num = 11;
// name = "meng11";
// sex = 'F';
}
Student::Student(int a ,string b,char c)
{
num = a;
name = b;
sex = c;
}
Student::~Student()
{
}
My_Student::My_Student(int a ,string b)
{
age = a;
addr = b;
}
student_pub.h
#ifndef _STUDENT_PUB__
#define _STUDENT_PUB__
#include<iostream>
#include<string>
using namespace std;
class Student
{
public:
Student();
Student(int a ,string b,char c);
~Student();
void display();
private:
int num;
string name ;
char sex;
};
class My_Student:public Student
{
public:
My_Student(int a ,string b);
void My_display(){
cout << "age : " << age <<endl;
cout << "addr : " << addr <<endl;
}
private:
int age;
string addr;
};
#endif
main.cpp
#include<iostream>
#include<string>
#include "student_pub.h"
using namespace std;
int main()
{
Student s1(1,"meng",'M');
// s1.num = 2; //
My_Student s2(27,"zhangjiang");
s2.display();
s2.My_display();
return 0;
}