代码链接:代码仓库
git clone https://gitee.com/etsuyou/cmake-template.git
模板
模板截图
如何使用
在src和inc中写代码
此处用我默认提供的代码
./go.sh cmake 生成Makefile
./go.sh make 生成bin文件和.a以及.so
./go.sh run app 运行
./go.sh clean 以及 ./go.sh clean-all 清理build中的内容
./go.sh -h -help --help 查看帮助
代码
CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(CTEST)
set(CMAKE_C_STANDARD 11)
include_directories(inc)file(GLOB_RECURSE SOURCESsrc/*.c
)
list(FILTER SOURCES EXCLUDE REGEX "src/math/.*")set(MATH_SOURCESsrc/math/add.csrc/math/minus.c
)option(BUILD_STATIC "Build static library" ON)
option(BUILD_SHARED "Build shared library" ON)
set(BUILD_TYPE "shared" CACHE STRING "Choose the build type: static, shared, or none")set(GENERATED_LIB_DIR_NAME lib)
set(GENERATED_PROGRAM_NAME app)set(ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${GENERATED_LIB_DIR_NAME})
set(LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${GENERATED_LIB_DIR_NAME})if(BUILD_STATIC)add_library(math_static STATIC ${MATH_SOURCES})set_target_properties(math_static PROPERTIESARCHIVE_OUTPUT_DIRECTORY ${ARCHIVE_OUTPUT_DIRECTORY} )
endif()if(BUILD_SHARED)add_library(math_shared SHARED ${MATH_SOURCES})set_target_properties(math_shared PROPERTIESLIBRARY_OUTPUT_DIRECTORY ${LIBRARY_OUTPUT_DIRECTORY} )
endif()add_executable(${GENERATED_PROGRAM_NAME} ${SOURCES})if(BUILD_TYPE STREQUAL "none")# do nothing
elseif(BUILD_TYPE STREQUAL "static")target_link_libraries(app math_static)
elseif(BUILD_TYPE STREQUAL "shared")target_link_libraries(app math_shared)
else()# do nothing
endif()# 添加一个自定义的 clean 目标
add_custom_target(clean-allCOMMAND ${CMAKE_COMMAND} -E remove -f ${CMAKE_BINARY_DIR}/*COMMAND ${CMAKE_COMMAND} -E remove_directory ${CMAKE_BINARY_DIR}/CMakeFilesCOMMAND ${CMAKE_COMMAND} -E remove_directory ${CMAKE_BINARY_DIR}/${GENERATED_LIB_DIR_NAME}COMMAND ${CMAKE_COMMAND} -E remove ${CMAKE_BINARY_DIR}/CMakeCache.txtCOMMENT "Cleaning all build files while preserving the build directory"
)# 你可以选择将 clean-all 目标添加到默认的清理操作中
# set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES "${CMAKE_BINARY_DIR}")message(STATUS "All tasks finished!")
go.sh
#!/bin/bash# 显示帮助信息的函数
show_help() {echo "用法: $0 <cmake|make|clean|clean-all|run> [app]"echo ""echo "选项:"echo " cmake 进入 build 目录并运行 cmake .."echo " make 进入 build 目录并运行 make"echo " clean 进入 build 目录并运行 make clean"echo " clean-all 进入 build 目录并运行 make clean-all"echo " run app 进入 build 目录并运行 ./app (app 是可执行文件的名称)"echo " -h, --help, -help 显示此帮助信息"
}# 检查参数数量
if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; thenecho "用法: $0 <cmake|make|clean|clean-all|run> [app]"exit 1
fi# 检查帮助参数
if [[ "$1" == "-h" || "$1" == "--help" || "$1" == "-help" ]]; thenshow_helpexit 0
fi# 进入 build 目录
if [ ! -d "build" ]; thenmkdir build
fi
cd build || exit# 根据参数执行相应的命令
case "$1" incmake)cmake ..;;make)make;;clean)make clean;;clean-all)make clean-all;;run)if [ -z "$2" ]; thenecho "错误: 运行应用程序时需要提供应用程序名称。"echo "用法: $0 run <app>"exit 1fi./"$2";;*)echo "无效的参数: $1"echo "用法: $0 <cmake|make|clean|clean-all|run> [app]"exit 1;;
esac