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) # 指定加载库
相关推荐
阿昭L2 天前
Windows通用的C/C++工程CMakeLists
c语言·c++·windows·makefile·cmake
梓䈑4 天前
【CMake】cmake实现属性传递的秘密(目标的默认输出路径 以及 如何修改输出路径)
c++·cmake
梓䈑6 天前
【CMake】cmake的3大核心:目标、属性 和 API(含大量重点函数解析)
c++·cmake
非鱼䲆鱻䲜10 天前
vscode开发stm32添加新的头文件路径和包含源文件
ide·vscode·stm32·cmake·包含头文件·包含源文件
特立独行的猫a11 天前
CMake与GN构建系统对比及GN使用指南
harmonyos·cmake·openharmony·构建·gn
特立独行的猫a11 天前
海思WS63平台CMake构建系统使用指南
cmake·海思·ws63·fbb_ws63
阿拉斯攀登12 天前
【RK3576 安卓 JNI/NDK 系列 05】NDK 构建系统:CMakeLists.txt 从入门到精通
cmake·rk3568·瑞芯微·rk安卓驱动·安卓jni·ndk构建系统
茉莉玫瑰花茶12 天前
CMake 工程指南 - 工程场景(4)
服务器·c++·cmake
茉莉玫瑰花茶12 天前
CMake 工程指南 - 工程场景(5)
开发语言·c++·cmake