理论
aux_source_directory 查找在某个路径下的所有源文件。
aux_source_directory(< dir > < variable >)
搜集所有在指定路径< dir >下的源文件的文件名,将输出结果列表储存在指定的变量< variable >中。
该命令旨在供使用显式模板实例化的项目使用。 模板实例化文件可以存储在Templates子目录中,并使用此命令自动收集,以避免手动列出所有实例化。
试图使用此命令来避免编写库或可执行目标的源文件列表。 尽管这似乎可行,但是CMake无法生成知道何时添加新源文件的生成系统。 通常,生成的构建系统知道何时需要重新运行CMake,因为修改了CMakeLists.txt文件以添加新的源。 当仅将源代码添加到目录而不修改该文件时,将不得不手动重新运行CMake来生成包含新文件的构建系统。
实践
内容
.
├── CMakeLists.txt
├── main.cc
├── MathFunction.cc
└── MathFunction.h
CMakeLists.txt 内容:
# CMake 最低版本号要求
cmake_minimum_required (VERSION 2.8)
# 项目信息
project (Demo2)
# 查找目录下的所有源文件
# 并将名称保存到 DIR_SRCS 变量
aux_source_directory(. DIR_SRCS)
# 指定生成目标
add_executable(Demo ${DIR_SRCS})
MathFunction.cc内容:
double power(double base, int exponent)
{
int result = base;
int i;
if (exponent == 0) {
return 1;
}
for(i = 1; i < exponent; ++i){
result = result * base;
}
return result;
}
MathFunction.h内容:
#ifndef POWER_H
#define POWER_H
extern double power(double base, int exponent);
#endif
main.cc内容:
#include <stdio.h>
#include <stdlib.h>
#include "MathFunction.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;
}
运行
$ mkdir build && cd build
$ cmake ..
$ make
$ ./Demo 2 3
2 ^ 3 is 8