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
分类:
C++工程
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人