栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用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 
#include 
#include 
#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配置
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/876803.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号