本文章將介紹Linux系統下,如何使用cmake將C++語言編譯成so文件 ,主要介紹如何安裝cmake和編譯,並使用python調用,細節如下:
一. Linux安裝cmake方法:
①下載cmake包,網址為:https://cmake.org/download/
我下載包為:cmake-3.23.1-linux-x86_64.tar.gz
②解壓:tar -zxvf cmake-3.23.1-linux-x86_64.tar.gz
③設置環境變量
執行
vim /etc/profile
在文件最后增加兩句
export CMAKE_HOME=/opt/cmake/cmake-3.23.1-linux-x86_64/bin # 包路徑,隨便安裝
export PATH=$CMAKE_HOME:$PATH
保存退出,刷新環境變量
source /etc/profile
檢驗是否安裝成功
cmake -version
二.編譯so文件需要准備的代碼如下,如下步驟:
① C++ 需要編譯的函數
#include "string.h" #include <iostream> #include <sstream> #include <stdio.h> using namespace std; extern"C" int addtest( int a ,int b); int addtest( int a ,int b) { cout<<a<<endl; cout<<b<<endl; return a+b; }
② CMakeLists.txt文件內容如下:
# cmake needs this line cmake_minimum_required(VERSION 3.23.1) # Define project name project(tj) add_library(tj SHARED tj.cpp)
③使用py文件調用
from ctypes import * import sys dll_test = CDLL("/data/sdv2/tangjunjun/mmdet2.19/cmake/dll1/build/libtj.so") a=dll_test.addtest(4,5) print(a)
使用python調用so文件結果: