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) # 指定加载库
相关推荐
草莓熊Lotso2 天前
【CMake】静态库的编译、链接与引用全解析
linux·c语言·数据库·c++·软件工程·cmake
郝学胜-神的一滴2 天前
CMake 012:Linux 下动态库与可执行程序的单文件构建
linux·服务器·开发语言·c++·软件构建·cmake
皮皮木子2 天前
rl_locomotion 编译过程三
编译·强化学习·cmake·蒸馏
郝学胜_神的一滴2 天前
CMake 012:Linux 下动态库与可执行程序的单文件构建
c++·cmake
皮皮木子2 天前
rl_locomotion 编译过程四
编译·cmake
dozenyaoyida5 天前
RISC-V嵌入式开发:彻底解决“undefined reference to isatty“错误全攻略
经验分享·c·cmake·嵌入式开发·isatty·没有定义问题
shanql5 天前
CMake笔记:Linux下常规使用
cmake
zh_xuan7 天前
Android JNI 动态注册:获取系统内存页大小
android·cmake·jni·ndk·动态注册·内存页大小
雪靡8 天前
Visual Studio 2026 优雅的给Cmake设置大代理
c++·ide·cmake·visual studio
郝学胜-神的一滴9 天前
CMake 011:跨平台动态库编译
开发语言·c++·嵌入式硬件·qt·程序人生·cmake·liunx