cmake-4

cmake-4學習,參考

瞭解

  • cmake的工作原理:

image-20221216000527838

  • Windows下用cmake編譯cmake

(1)先下載cmake(exe)

(2)編譯源碼文件

# -S表示源文件夾下;-B表示新建一個文件夾build,並將編譯結果放在該文件build:【生成】
cmake -S . -B build
  
# -G 使用nmake,指定編譯工具
cmake -S . -B build -G "NMake Makefiles"
  
# 生成Xcode執行的文件,
cmake -S . -B xcode -G "Xcode"
  
# 直接打開xcode項目
cmake --open xcode
  
# --build 執行編譯(位置)和make功能一樣:【編譯】
cmake --build build
 
# -j:支持多線程編譯和和make一樣
cmake --build build -j8
  
# --config 指定編譯方式:Release或者Debug
cmake --build build --config Release

# --install 指定安裝位置
cmake --install build

動態庫和靜態庫

image-20221224175704223

  • 靜態庫:編譯後的二進制代碼,類似.o【編譯時鏈接】

.lib文件:windows

.a文件:linux

舉例:linux生成靜態庫

// xlog.h
#ifndef XLOG
#define XLOG
class xlog
{
public:
    xlog();
};

#endif

// xlog.cpp
#include "xlog.h"
#include <iostream>
using namespace std;

xlog::xlog()
{
    cout << "print xlog" << endl;
}

# CMakeLists.txt
cmake_minimum_required(VERSION 3.20)

project(xlog)
# STATIC:表示生成靜態庫
add_library(xlog STATIC xlog.cpp xlog.h)

然後執行:

# 生成
cmake -S . -B build
# 編譯
cmake --build build

image-20221224155203769

舉例:鏈接靜態庫

在test_xlog/test_xlog.cpp中鏈接libxlog.a庫

// test_xlog.cpp
#include <iostream>
#include "xlog.h"
using namespace std;

int main()
{
    xlog log;
    cout << "test_xlog" << endl;
    return 0;
}

# CMakeLists.txt
cmake_minimum_required(VERSION 3.20)

project(test_xlog)

#指定頭文件查找路徑
include_directories("../xlog")

#指定庫查找路徑
link_directories("../xlog/build")

add_executable(test_xlog test_xlog.cpp)

#指定加載的庫【靜態庫:libxlog.a】
target_link_libraries(test_xlog xlog)
  • 動態庫: 【運行時鏈接】

.lib文件(函數地址索引)和.dll文件(函數二進制代碼):windows

.so文件:linux

.dylib:macOS

舉例:生成動態庫並鏈接使用

# CMakeLists.txt
cmake_minimum_required(VERSION 3.20)
project(xlog)

include_directories("xlog")

# 編譯生成動態庫
add_library(xlog SHARED xlog/xlog.cpp)

add_executable(test_xlog test_xlog/test_xlog.cpp)
target_link_libraries(test_xlog xlog)

image-20221224181213903

注意:在windows中生成鏈接動態庫時,需要設置一下才能同時生成:.dll和.lib文件,下面是兼容各平臺的代碼:

// xlog.h
#ifndef XLOG
#define XLOG

#ifndef _WIN32
    #define XCPP_API
#else
    #ifdef xlog_EXPORTS
        #define XCPP_API __declspect(dllexport) //庫項目調用
    #else
        #define XCPP_API __declspect(dllimport) //調用庫項目調用
    #endif
#endif
class XCPP_API xlog
{
public:
    xlog();
};
#endif
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章