目的
- 熟悉使用cmakelists编译c++代码过程
- 编译动态库so给其他语言调用
操练
准备
环境:mac环境上测试
- 安装cmake
- 安装vscode
- 配置includePath:首选项->settings->搜索includePath
第三方库安装
$ brew install opencv
$ brew install curl
构建项目
extern "C"
{
int addsum(int a, int b);
}
int addsum(int a, int b)
{
return a + b;
}
#include "addsum.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;
}
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配置
|