1. 单目标文件
main.c
#include <stdio.h> #include <stdlib.h> 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; } 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_minimum_required (VERSION 2.8) # 指定最低的版本号 # 项目信息 project (Demo01_cmake) # 指定生成目标 add_executable(Demo_exe main.c) # Demo_exe为生成的可执行文件 main.c为依赖文件
然后
cmake . # 生成makeFile文件
make # 执行make
2. 同一个目录,多个源文件
calc_power.h
double power(double a, int b);
calc_power.c
#include "calc_power.h" 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; }
main.cpp
#include <stdio.h> #include <stdlib.h> #include "calc_power.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_minimum_required (VERSION 2.8) # 项目信息 project (Demo2_cmake) # 指定生成目标 # add_executable(Demo2_cmake main.c calc_power.c) # 如果源文件多,这样写麻烦 # 该命令会查找指定目录下的所有源文件, 然后将结果存到指定变量名 # 如下: 查找当前目录下的所有源文件, 并将名称报错到 DIR_SRCS 变量 aux_source_directory(. DIR_SRCS) # 指定生成目标 # CMake 会将当前目录所有源文件名赋值给变量 DIR_SRCS # 再指示变量 DIR_SRCS 中源文件 编译成一个 Demo2_exe的可执行文件 add_executable(Demo2_exe ${DIR_SRCS})
再执行
cmake . make