CMake快速使用

基础使用

建立CMakeLists.txt

c 复制代码
cmake_minimum_required(VERSION 3.18) # 设定最小的CMake版本要求

project(first_cmake)    # 定义项目名称

add_executable(first_cmake first_cmake.cpp) # 添加可执行文件,指定源文件为first_cmake.cpp

建立文件first_cmake.cpp

cpp 复制代码
#include <iostream>
using namespace std;

int main(int argc,char *argv[])
{
    cout<<"first cmake c++"<<endl; 
    return 0;
}

生成项目文件

编译

CMake编译静态库

cpp 复制代码
cmake_minimum_required(VERSION 3.18) # 设定最小的CMake版本要求

project(xlog)    # 定义项目名称
add_library(xlog STATIC xlog.cpp) # 添加静态库,指定源文件为xlog.cpp
add_executable(first_cmake xlog.cpp)

CMake链接静态库

结构:

  1. 先生成静态库
c 复制代码
cmake_minimum_required(VERSION 3.18)

project(xlog)

add_library(xlog STATIC xlog.cpp)
  1. 包含对应的头文件
cpp 复制代码
#include <iostream>
using namespace std;
#include "xlog.h"

int main(int argc,char *argv[])
{
    Xlog log;
    cout << "test xlog" << endl; 
    return 0;
}
  1. 指定库路径和名称
cpp 复制代码
cmake_minimum_required(VERSION 3.18)
project(test_xlog)
include_directories("../xlog") # 添加头文件搜索路径,指向xlog目录
link_directories("../xlog/build") # 指定库查找路径
add_executable(test_xlog testxlog.cpp)
target_link_libraries(test_xlog xlog) # 指定加载库

CMake链接动态库

结构:

  1. 创建动态库
  2. 链接
cpp 复制代码
cmake_minimum_required(VERSION 3.20)
project(xlog)
include_directories("xlog") # 指定头文件搜索路径
add_library(xlog SHARED xlog/xlog.cpp) # 生成共享库
add_executable(test_xlog test_xlog/testxlog.cpp) # 生成可执行文件
target_link_libraries(test_xlog xlog) # 指定加载库
相关推荐
瞎折腾啥啊1 天前
CMake FetchContent与ExternalProject
c++·cmake·cmakelists
JMchen1231 天前
集成第三方 C/C++ 库到 Android NDK 项目:OpenCV 与 FFmpeg 实战指南
opencv·ffmpeg·音视频开发·cmake·jni·ndk·abi 兼容性
郝学胜-神的一滴3 天前
从零起步:CMake基础入门与实战跨平台编译
c++·软件工程·软件构建·cmake
AlbertS4 天前
distcc + ccache 编译递归问题排查总结
c++·cmake·gcc·g++·distcc·ccache
Robot_Nav6 天前
CMake、Ament 与 Catkin:ROS 构建系统的前世今生
ros·cmake
CoderMeijun10 天前
CMake 入门笔记
c++·笔记·编译·cmake·构建工具
郝学胜-神的一滴10 天前
墨韵技术|CMake:现代项目构建的「行云流水」之道
c++·程序人生·软件工程·软件构建·cmake
H Journey12 天前
C++之 CMake、CMakeLists.txt、Makefile
开发语言·c++·makefile·cmake
H Journey13 天前
VSCode下CMake使用
vscode·cmake
9分钟带帽13 天前
vscode中配置Qt6和CMake的开发环境
c++·vscode·cmake