CMake生成靜態庫


目錄結構

文件內容
  • Hello.h
#ifndef MYSHAREDLIB_HELLO_H
#define MYSHAREDLIB_HELLO_H
 
// 打印 Hello World!
void hello();
 
// 使用可變模版參數求和
template <typename T>
T sum(T t)
{
    return t;
}
template <typename T, typename ...Types>
T sum(T first, Types ... rest)
{
    return first + sum<T>(rest...);
}
 
#endif
  • Hello.cpp
#include <iostream>
#include "Hello.h"
 
void hello() {
    std::cout << "Hello, World!" << std::endl;
}
  • main.cpp
#include <iostream>
#include "Hello.h"
using std::cout;
using std::endl;
 
int main() {
 
    hello();
    cout << "1 + 2 = " << sum(1,2) << endl;
    cout << "1 + 2 + 3 = " << sum(1,2,3) << endl;
 
    return 0;
}
cmake基本腳本
#cmake版本
cmake_minimum_required(VERSION 3.5)

# 項目名稱
project(hello_library)

# 根據庫文件代碼生成靜態庫
add_library(hello_library STATIC src/Hello.cpp)

# 包含指定頭文件所在的目錄
target_include_directories(hello_library PUBLIC  ${PROJECT_SOURCE_DIR}/include/static)

# 創建可執行程序
add_executable(hello_binary src/main.cpp)

# 鏈接靜態庫文件
target_link_libraries( hello_binary PRIVATE hello_library)
編譯
mkdir build
cd build
cmake ..
make
./hell_binary
返回結果
Hello, World!
1 + 2 = 3
1 + 2 + 3 = 6


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM