CMake1-4:静态库编译、动态库编译(生成库文件)【add_library(xlog STATIC xlog.cpp xlog.h)】【利用关键字STATIC/SHARED指定生成静/动态库】

一、项目代码

 xlog.h

//xlog.h
#ifndef XLOG_H
#define XLOG_H

class XLog
{
public:
	XLog();
};
#endif

xlog.cpp

#include "xlog.h"
#include <iostream>
using namespace std;
XLog::XLog()
{
	cout<<"Create XLog"<<endl;
}

二、CMake编译静/动态库

1、CMake编译静态库【STATIC】

#CMakeLists.txt
cmake_minimum_required(VERSION 3.20)
project(xlog)
add_library(xlog STATIC xlog.cpp xlog.h)

在xlog目录下执行:

cmake -S . -B build
-- The C compiler identification is GNU 11.3.0
-- The CXX compiler identification is GNU 11.3.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /build

再执行:

cmake --build build

 静态库打印如下:

[ 50%] Building CXX object CMakeFiles/xlog.dir/xlog.cpp.o
[100%] Linking CXX static library libxlog.a
[100%] Built target xlog

2、CMake编译动态库【SHARED】

#CMakeLists.txt
cmake_minimum_required(VERSION 3.20)
project(xlog)
add_library(xlog SHARED xlog.cpp xlog.h)

在xlog目录下执行:

cmake -S . -B build
-- The C compiler identification is GNU 11.3.0
-- The CXX compiler identification is GNU 11.3.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /build

再执行:

cmake --build build

  动态库打印如下:

[ 50%] Building CXX object CMakeFiles/xlog.dir/xlog.cpp.o
[100%] Linking CXX shared library libxlog.so
[100%] Built target xlog

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值