- 项目文件体系
root_dir
|---- CMakeLists.txt # root_cmake
|---- *.cpp *.h
|---- main.cpp
|----- common # include as file 以文件形式加入
|---- *.cpp *.h
|----- proto # include as subproject 以子项目形式加入
|---- CMakeLists.txt #proto_cmake
|---- *.cpp *.h
|---- 3rd
|---- include/nlohman/json.hpp # 以源码形式加入 三方库
|---- xlnt-1.5.0 # 以静态库形式加入三方库
|---- /include/xlnt/*.hpp
|---- lib/libxlnt.a
- root_camke文件
cmake_minimum_required(VERSION 3.5)
project(radarTestWidget LANGUAGES CXX)
# add root_dir and common header source file
FILE(GLOB SC_FILES "*.cpp" "*.h" "*.ui" "common/*.cpp" "common/*.h")
set(PROJECT_SOURCES
${SC_FILES}
${TS_FILES}
)
# add goole protobuf
find_package(Protobuf REQUIRED)
include_directories(${Protobuf_INCLUDE_DIRS})
#add_subdirectory(common)
add_subdirectory(proto)
include_directories("3rdParty/xlnt-1.5.0/include" "3rdParty/include") # add include dir
link_directories("3rdParty/xlnt-1.5.0/lib") # add link library dir
add_executable()(${PROJECT_NAME} ${PROJECT_SOURCES})
# link
target_link_libraries(radarTestWidget PRIVATE
Qt${QT_VERSION_MAJOR}::Widgets
xlnt
proto
)
3 proto_cmake
#set the project name
project (proto)
# Add a library with the above sources
FILE(GLOB SC_FILES "*.cc" "*.h" "*/*.cc" "*/*.h")
set(PROJECT_SOURCES ${SC_FILES})
find_package(Protobuf REQUIRED) # add installed lib in /usr/local/lib
include_directories(${Protobuf_INCLUDE_DIRS})
include_directories(${CMAKE_CURRENT_BINARY_DIR})
add_library(${PROJECT_NAME} ${PROJECT_SOURCES})
target_include_directories( ${PROJECT_NAME}
PUBLIC
${PROJECT_SOURCE_DIR}
)
target_link_libraries( ${PROJECT_NAME}
PUBLIC
${Protobuf_LIBRARIES})
- main.cpp include lib
#include "common/__.h"
#include "xlnt/xlnt.hpp"
#include "nlohmann/json.hpp"
#include <iostream>
#include <google/protobuf/text_format.h>
-
其它cmake小技巧
set(CMAKE_EXPORT_COMPILE_COMMANDS ON) 开启输出编译数据库,compile_commands.json -
静态链接 & 指定静态库链接
cmake_minimum_required(VERSION 3.10)#规定cmake的最低版本要求
project(second_try)#项目的名称,不一定和你的文件夹名称一样
#set(CMAKE_CXX_COMPILER "g++")#设置c++编译器
# 优先选用静态库
set(CMAKE_FIND_LIBRARY_SUFFIXES ".a" ".so")
# 使用静态链接
set(CMAKE_EXE_LINKER_FLAGS "-static")
message(${PROJECT_NAME})
find_package(Threads)
# include_directories(${PROJECT_SOURCE_DIR}/include)#添加头文件的搜索路
# add protobuf
include_directories(/usr/local/include)
set(LIB_PROTOBUF /path/to/protobuf/libprotobuf.a)
aux_source_directory(src SrcFiles)#将源文件列表写在变量SrcFiles中
aux_source_directory(src/proto ProtoSrcFiles)#工程项目较大,要创建多个模块
add_executable(main ${SrcFiles} ${TestSrcFiles} ${ProtoSrcFiles})#设置可执行文件的名称,make之后bin目录下出现main.exe
target_link_libraries(main ${CMAKE_THREAD_LIBS_INIT} ${LIB_PROTOBUF} ${LIB_JSON_CPP})