使用cmake编译c项目并给其他语言调用过程

目的

  • 熟悉使用cmakelists编译c++代码过程
  • 编译动态库so给其他语言调用

操练

准备

环境:mac环境上测试

  • 安装cmake
  • 安装vscode
  • 配置includePath:首选项->settings->搜索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})

编译

  • 生成makefile
$ 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配置

猜你喜欢

转载自blog.csdn.net/xzpdxz/article/details/124689491
今日推荐