添加链接描述
上述文章中详细介绍了cmake
这里将给出几个案例
先是定义一个man.cpp:
#include<iostream>
using namespace std;
int main(){
cout<<"Hello cmake....";
return 0;
}
然后在main.cpp相同目录下 创建一个CMakeLists.txt文件(注意名名字不要写错)
#Cmake 最低版本的要求
cmake_minimum_required (VERSION 2.8)
#项目的信息
project (Demo1)
#指定生成目标 Demo
add_executable(Demo main.cpp)
#
在相同目录下建一个build文件夹 在build文件夹内输入以下指令
cmake ..
make
./Demo
这样就可以运行了.这是最简单版本的cmake
下面展示同一目录,多个源文件,
在同一个问件夹下 分别建立
MathFunctions.h
#ifndef POWER_H
#define POWER_H
extern double power(double base, int exponent);
#endif
#ifndef POWER_H
#define POWER_H
extern double power(double base, int exponent);
#endif
#include <stdio.h>
#include <stdlib.h>
#include "MathFunctions.h"
int main(int argc, char *argv[])
{
if (argc < 3){
printf("Usage: %s base exponent \n", argv[0]);
return 1;
}
double base = atof(argv[1]);
int exponent = atoi(argv[2]);
double result = power(base, exponent);
printf("%g ^ %d is %g\n", base, exponent, result);
return 0;
}
我们可以这样写一个CMakeLists.txt
# CMake 最低版本号要求
cmake_minimum_required (VERSION 2.8)
# 项目信息
project (Demo2)
# 指定生成目标
add_executable(Demo main.cc MathFunctions.cc)
# 唯一的改动就是在add_executable中加入了一个MathFunctions.cc的源文件
#这样写完全可以 但是将所有的源文件都加进去就会显得比较繁琐
但是会存在着一些缺陷
于是改用下面这个
#CMake 最低版本号要求
cmake_minimum_required (VERSION 2.8)
# 项目信息
project (Demo2)
# 查找目录下的所有源文件
#这是一个较为省事的方法 就是将所有源文件到一个目录下 然后
#该指令会会查找指定目录下的所有源文件 ' . '表示当前目录下
# 并将名称保存到 DIR_SRCS 变量
aux_source_directory(. DIR_SRCS)
#这样CMake会将当前目录所有的源文件名赋值给DIR_SRC
# 指定生成目标
#指示变量DIR_SRC中的源文件需要编译成一个名称为Demo可执行文件
add_executable(Demo ${DIR_SRCS})
多个目录,多个源文件
现在进一步将 MathFunctions.h 和 MathFunctions.cc 文件移动到 math 目录下。
./Demo3
|
+--- main.cc
|
+--- math/
|
+--- MathFunctions.cc
|
+--- MathFunctions.h
在math目录下编写一个CMakeLists.txt
# 查找当前目录下的所有源文件
# 并将名称保存到 DIR_LIB_SRCS 变量
aux_source_directory(. DIR_LIB_SRCS)
# 指定生成 MathFunctions 链接库
add_library (MathFunctions ${DIR_LIB_SRCS})
#使用命令add_library 将目录中的源文件编译成静态库
然后重写main.cc文件
#include <stdio.h>
#include <stdlib.h>
#include "math/MathFunctions.h"
int main(int argc, char *argv[])
{
if (argc < 3){
printf("Usage: %s base exponent \n", argv[0]);
return 1;
}
double base = atof(argv[1]);
int exponent = atoi(argv[2]);
double result = power(base, exponent);
printf("%g ^ %d is %g\n", base, exponent, result);
return 0;
}
再写一个CMakeLists.txt文件
# CMake 最低版本号要求
cmake_minimum_required (VERSION 2.8)
# 项目信息
project (Demo3)
# 查找目录下的所有源文件
# 并将名称保存到 DIR_SRCS 变量
aux_source_directory(. DIR_SRCS)
# 添加 math 子目录
#指明本项目中还有一个子目录
add_subdirectory(math)
# 指定生成目标
add_executable(Demo ${DIR_SRCS})
# 添加链接库
#指明可执行文件Demo 还需要连接一个名为MathFunctions的链接库
target_link_libraries(Demo MathFunctions)
具体说明我在CMakeLists.txt文件中表明了