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) # 指定加载库
相关推荐
blueman88884 小时前
Qt5通过vcpkg中调用时,在debug模式下调试时总是调用release的plugins文件夹中的dll
c++·qt·cmake
郝学胜-神的一滴7 天前
CMake 038:OBJECT目标复用编译+Linux动态库版本自动化管理
linux·c++·程序人生·软件工程·软件构建·cmake·工程配置
郝学胜_神的一滴9 天前
CMake 037:宏传递流转机制与C++编译特性跨平台适配指南
c++·cmake
郝学胜_神的一滴12 天前
CMake 034:生成器表达式:解耦构建时序、精简分支逻辑的终极利器
c++·cmake
郝学胜_神的一滴16 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
郝学胜_神的一滴18 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
郝学胜_神的一滴20 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
郝学胜_神的一滴25 天前
CMake 021: IF 条件判据详诠
c++·cmake
郝学胜-神的一滴1 个月前
CMake 019:程序生成与清理全解析
开发语言·c++·qt·程序人生·软件构建·cmake
郝学胜_神的一滴1 个月前
CMake 018:解决头文件编译失效\&VS项目无法展示头文件难题
c++·cmake