C++工程(二):学习使用CMake构建C++工程
CMake --> Makefile/Ninja/MSVC
CMake解决了makefile、MSVC不能跨平台的问题,ninja可以适用于Linux和Windows系统
cmake -S . -B build -D # 指定Release/Debug
cmake --build build
CMake常用语法:
- add_library
- add_executable
Example 1
# cmake needs this line
cmake_minimum_required(VERSION 3.1)
# Define project name
project(opencv_example_project)
# Find OpenCV, you may need to set OpenCV_DIR variable
# to the absolute path to the directory containing OpenCVConfig.cmake file
# via the command line or GUI
find_package(OpenCV REQUIRED)
# If the package has been found, several variables will
# be set, you can find the full list with descriptions
# in the OpenCVConfig.cmake file.
# Print some message showing some of them
message(STATUS "OpenCV library status:")
message(STATUS " config: ${OpenCV_DIR}")
message(STATUS " version: ${OpenCV_VERSION}")
message(STATUS " libraries: ${OpenCV_LIBS}")
message(STATUS " include path: ${OpenCV_INCLUDE_DIRS}")
# Declare the executable target built from your sources
add_executable(opencv_example example.cpp)
# Link your application with OpenCV libraries
target_link_libraries(opencv_example PRIVATE ${OpenCV_LIBS})
总结Summary
CMake相较于Makefile 的优势:
- CMake可以跨平台(Makefile for Linux)
- CMake的底层即为Makefile (Darknet版本的YOLO就是用makefile来组织工程的)
应知应会
- 通过
cmake --version查看CMake版本 - CMake Debug和Release设置
- CMake默认的编译模式是Debug,Release模式的运行速度要快于Debug
- 需要注意的是:
add_executable需要在target_include_directories和target_link_libraries之前- 添加
exe之后才可以include头文件和链接库
- 添加
add_executable:添加可执行文件,add_library:生成 [STATIC | SHARED | ... ] 库文件CMAKE_DL_LIBS动态库加载相关的lib- CMake关于Warnings
- cmake 添加头文件目录,链接动态、静态库
- 不同gcc编译器对C++版本的支持
- CMake vs Ninja

浙公网安备 33010602011771号