CMakelist編譯靜態庫和動態庫
阿新 • • 發佈:2018-12-03
從程式碼模組化的角度,往往需要將一個系統工程拆分成很多小的模組,編譯成庫函式也是很好的方法。
編譯庫函式的時候,可以選擇編譯成靜態庫或者動態庫。靜態庫對應.a檔案,動態庫對應.so檔案。
還是以氣泡排序為例加以說明。
編寫StaticBubble.h標頭檔案,裡面定義函式但是不實現。路徑在系統工程下的include資料夾下。
using namespace std;
void bubbleSort(int array[], int num);
在系統工程下的src資料夾下建立StaticBubble.cpp檔案,用於實現上面標頭檔案中定義的函式。
在src資料夾下建立測試程式testBubble.cpp,裡面需要包含main函式。#include <iostream> using namespace std; void bubbleSort(int array[], int num){ for(int i = 0; i < num; i++){ for(int j = 0; j < num - i - 1; j++){ if(array[j] > array[j + 1]){ int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } }
#include <iostream>
#include <StaticBubble.h>
using namespace std;
int main(int argc, char **argv){
int array[5] = {32,54,38,65,98};
bubbleSort(array, 5);
for(int i = 0; i < 5; i++){
cout << array[i] << ‘\t’;
}
cout << endl;
}最後編寫CMakelist:
cmake_minimum_required(VERSION 3.7)
project(Static_Lib)
set(CMAKE_CXX_STANDARD 11)
include_directories(include)
add_library(StaticBubble STATIC src/StaticBubble.cpp) #STATIC or SHARED
#set(SOURCE_FILES include/StaticBubble.h src/testBubble.cpp src/StaticBubble.cpp)
add_executable(Static_Lib src/testBubble.cpp)
target_link_libraries(Static_Lib StaticBubble)
上面add_library中可以選擇STATIC或者預設,代表編譯成靜態庫,即.a檔案;選擇SHARED時,編譯成動態庫。
執行即可。