github: https://github.com/ZhouHanyu18/cmake
一、多目录编译demo1
1. 文件结构
2. main.cpp
#include <stdio.h>
#include <stdlib.h>
#include "../tools/math.h"
int main(int argc, char* argv[]) {
if (argc < 2) {
printf("please input %s number: \n", argv[0]);
return 1;
}
double input = atof(argv[1]);
int n = atoi(argv[2]);
double out = pow(input, n);
printf("pow(%f, %d) is %f\n", input, n, out);
return 0;
}
3. tools/
math.h
#ifndef MyMath
#define MyMath
double pow(double a, int n);
#endif // MyMath
math .cpp
#include "math.h"
double pow(double a, int n) {
double ret = 1;
for (int i = 0; i < n; ++i) {
ret *= a;
}
return ret;
}
4. tools/CMakeLists.txt
# 查找当前目录下的所有源文件, 并将名称保存到 DIR_LIB_SRCS 变量
aux_source_directory(. DIR_LIB_SRCS)
# 生成链接库
add_library (Tools ${DIR_LIB_SRCS})
5. CMakeLists.txt
# cmake 最低版本要求
cmake_minimum_required (VERSION 2.8)
# 项目名称
project (Main)
# 查找当前目录下的所有源文件, 并将名称保存到 DIR_SRCS 变量
aux_source_directory(main/ DIR_SRCS)
# 指定生成目标
add_executable(main ${DIR_SRCS})
# 添加 math 子目录
add_subdirectory(tools)
# 添加链接库
target_link_libraries(main Tools)