參考: https://www.hahack.com/codes/cmake/ui
1. 單目標文件
main.cspa
#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.txtcode
cmake_minimum_required (VERSION 2.8) # 指定最低的版本號 # 項目信息 project (Demo01_cmake) # 指定生成目標 add_executable(Demo_exe main.c) # Demo_exe爲生成的可執行文件 main.c爲依賴文件
而後 blog
cmake . # 生成makeFile文件
make # 執行make
2. 同一個目錄,多個源文件
calc_power.hget
double power(double a, int b);
calc_power.cio
#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.txttable
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})
再執行class
cmake . make
3. 多目錄,多文件
main.crequire
#include <stdio.h> #include <stdlib.h> #include "./mymath/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; }
mymath的目錄下CMakeLists.txt
# 查找當前目錄下的全部源文件 # 並將名稱保存到 DIR_LIB_SRCS 變量 aux_source_directory(. DIR_LIB_SRCS) # 生成連接庫 # 使用add_library 將src目錄中的源文件編譯成靜態連接庫 add_library(calc_power $(DIR_LIB_SRCS))
main.c所在的目錄下的CMakeLists.txt
# Make 最低版本號要求 cmake_minimum_required (VERSION 2.8) # 項目信息 project (Demo3_cmake) # 查找當前目錄下的全部源文件 # 並將名稱保存到 DIR_SRCS 變量 aux_source_directory(. DIR_SRCS) # 添加 math 子目錄, 這樣mymath目錄下的 CMakeLists.txt文件和源代碼也會被處理 add_subdirectory(mymath) # 指定生成目標 add_executable(Demo3_exe main.c) # 添加連接庫, 指明可執行文件Demo3_exe 須要鏈接一個名爲 calc_power的連接庫 target_link_libraries(Demo3_exe calc_power)
而後:
cmake . make