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) # 指定加载库
相关推荐
明月_清风10 小时前
Makefile 完全指南:从入门到 CMake 工程化实践
后端·cmake
yuanyuan2o22 天前
从最小项目开始的 CMake 教程
c语言·开发语言·arm开发·c++·makefile·make·cmake
瞎折腾啥啊5 天前
VCPKG详细使用教程
linux·c++·cmake·cmakelists
郝学胜-神的一滴8 天前
跨平台动态库与头文件:从原理到命名的深度解析
linux·c++·程序人生·unix·cmake
吃鱼鱼鱼9 天前
CMakeListsc常用路径详解
cmake
瞎折腾啥啊11 天前
vcpkg与CMake
linux·c++·cmake·cmakelists
众少成多积小致巨12 天前
Cmake 入门指南
cmake
瞎折腾啥啊13 天前
现代 CMake 目标系统
c++·cmake·cmakelists
H Journey13 天前
常用知识总结C++、CMake、Linux
linux·c++·opencv·cmake
H Journey14 天前
Windows + VSCode + CMake 编译
windows·vscode·cmake