目的
- cmakelist を使用して C++ コードをコンパイルするプロセスに精通している
- 動的ライブラリをコンパイルして他の言語から呼び出す
練習する
準備する
環境:Mac環境でテスト済み
- cmakeをインストールする
- vscodeをインストールする
- includePath を構成します: [設定] -> [設定] -> [includePath を検索]
サードパーティライブラリのインストール
$ brew install opencv # apt install opencv # ubuntu
$ brew install curl # apt install curl # ubuntu
プロジェクトのビルド
- src/addsum.h
extern "C"
{
int addsum(int a, int b);
}
- src/addsum.cpp
int addsum(int a, int b)
{
return a + b;
}
- src/so_test.c
#include "addsum.cpp"
- src/main.cpp
#include "iostream"
#include "stdio.h"
#include <curl/curl.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "addsum.h"
int main(int argc, char const *argv[])
{
printf("hello wolrd");
cv::Mat img = cv::imread("./aaa.jpeg");
int su = addsum(1, 3);
std::cout << su << std::endl;
cv::imshow("test", img);
cv::waitKey(0);
return 0;
}
- CMakeLists.txt
cmake_minimum_required(VERSION 3.9) #最低版本
#设置项目名称
SET(PROJECT_NAME Test1)
project(Test1 VERSION 1.0) #项目名称及自定义版本号
FIND_PACKAGE(OpenCV REQUIRED)
INCLUDE_DIRECTORIES(${OpenCV_INCLUDE_DIRS})
AUX_SOURCE_DIRECTORY(src DIR_SRCS)
SET(TEST_MATH ${DIR_SRCS})
ADD_EXECUTABLE(${PROJECT_NAME} ${TEST_MATH})
add_library(utils SHARED src/so_test.c)
TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${OpenCV_LIBS})
コンパイル
- メイクファイルの生成
$ cmake .
- コンパイル
$ make
- 結果
$ ls -l
-rw-r--r-- 1 root staff 14362 5 10 12:58 CMakeCache.txt
drwxr-xr-x 13 root staff 416 5 10 15:33 CMakeFiles
-rw-r--r-- 1 root staff 436 5 10 14:35 CMakeLists.txt
-rw-r--r-- 1 root staff 6773 5 10 14:35 Makefile
-rwxr-xr-x 1 root staff 118784 5 10 15:33 Test1 # 生成的可执行文件
-rw-r--r-- 1 root staff 146304 5 10 11:16 aaa.jpeg
drwxr-xr-x 8 root staff 256 5 10 14:35 build
-rw-r--r-- 1 root staff 1542 5 10 12:27 cmake_install.cmake
-rwxr-xr-x 1 root staff 16472 5 10 14:55 libutils.dylib # 生成的动态库,用于给其他语言调用
drwxr-xr-x 6 root staff 192 5 10 14:54 src
実行可能ファイルを実行する
$ ./Test1
hello wolrd4 # 还有一张图
その他の言語での通話の場合
- 場合
from ctypes import cdll
def main():
so = cdll.LoadLibrary('./libutils.dylib')
res = so.addsum(1, 3)
print(res)
if __name__ == '__main__':
main()
- 結果
4
要約する
- サードパーティ ライブラリのインストールは、システムのインストールに直接対応します。
- 他の言語に対して普遍的に呼び出す必要がある場合は、最後に c を使用して C++ コードをラップします。
- エディターのプロンプトは includePath を使用して構成するのが最適です