1. 程式人生 > 其它 >linux系統下使用cmake編譯so檔案

linux系統下使用cmake編譯so檔案

本文章將介紹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檔案結果: