# LearningCmake **Repository Path**: zh1715700508/learning-cmake ## Basic Information - **Project Name**: LearningCmake - **Description**: No description available - **Primary Language**: C++ - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-02-16 - **Last Updated**: 2022-01-21 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # LearningCmake #### 介绍 简单的学习了用Cmake构建C/C++工程 # 编译静态库以及直接编译 编译./src的源文件,其头文件目录为./inc,项目根目录为main.c和main.cpp(分别编译c和c++文件) 1. 直接从源文件和头文件编译 ```cmake # CMakeLists.txt 直接包含头文件和源文件,文件结构为 ./src/*.c ./inc/*.h ./src/main.cpp cmake_minimum_required(VERSION 3.0.0) project(linklist) # 添加源文件路径 aux_source_directory(./src LIB_SRC) # 下面的语句和上面的语句意思应该是一致的 # set(SOURCES # src/Linklist.c # src/base64.c # src/main.cpp # ) # 添加要编译的可执行文件 add_executable(linklist ${LIB_SRC}) # add_executable(linklist main.cpp ${LIB_SRC}) # target_include_directories(linklist PRIVATE ${PROJECT_SOURCE_DIR}/inc ) ``` 2. 编译静态库,然后从静态库编译工程 ```cmake # CMakeLists.txt 编译静态库,文件结构为 ./src/*.c ./inc/*.h ./main.c cmake_minimum_required(VERSION 3.1) project(hello) # 添加搜索路径 aux_source_directory(./src LIB_SRC) # 生成静态库,Mylib和路径之间不加其他命令表示STATIC add_library(Mylib ${LIB_SRC}) # 添加目标的引用路径,目标为Mylib,同时也为hello target_include_directories(Mylib PUBLIC ${PROJECT_SOURCE_DIR}/inc) # 设置PUBLIC,main.c才能引用头文件 # 添加可执行文件 add_executable(hello main.c) #添加目标的链接库,此时目标为hello target_link_libraries(hello Mylib) ``` 3. 使用已经编译好的静态库,然后编译可执行文件 ```cmake # CMakeLists.txt 使用静态库编译,文件结构为 ./src/*.c ./inc/*.h ./main.cpp cmake_minimum_required(VERSION 3.1) project(hello) aux_source_directory(./src LIB_SRC) # 静态库的地址 link_directories(./static_lib) # 包含路径,不能使用target_include_directory,因为这不属于构建hello时的 include_directories(${PROJECT_SOURCE_DIR}/inc) add_executable(hello main.cpp) target_link_libraries(hello Mylib) # 库名称不用加lib ```