windows下cmake C++库打包成C方式导出

背景

windows下当前的一个项目使用的编译器是mingw,想要使用一个使用msvc编译出来的C++库。

方法

重新创建一个库,这个使用extern "C"方式导出函数,在函数中调用msvc编译出来的库。

项目文件

文件结构

|-- CMakeLists.txt
|-- floor_calibration
|   |-- include
|   |   |-- floor_calibration.h
|   |   `-- floor_calibration_dll_global.h
|   `-- x64Windows
|       |-- floor_calibration.dll
|       `-- floor_calibration.lib
|-- floor_calibration_c.cc
`-- floor_calibration_c.h

CMakeLists.txt

cmake_minimum_required(VERSION 3.20)

project(floor_calibration_c)

set(CMAKE_CXX_STANDARD 17)

add_library(${PROJECT_NAME} SHARED floor_calibration_c.cc)

# 这里添加一个宏定义,可以“传递”到代码中,影响代码中的宏判断
target_compile_definitions(${PROJECT_NAME} PUBLIC -DFLOOR_CALIBRATION_DLL_LIBRARY) 

target_include_directories(${PROJECT_NAME} PRIVATE floor_calibration/include)
target_link_directories(${PROJECT_NAME} PRIVATE floor_calibration/x64Windows)

target_link_libraries(${PROJECT_NAME} floor_calibration)

floor_calibration_c.h

#if defined(_MSC_VER) || defined(WIN64) || defined(_WIN64) || defined(__WIN64__) || defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
#  define Q_DECL_EXPORT __declspec(dllexport)
#  define Q_DECL_IMPORT __declspec(dllimport)
#else
#  define Q_DECL_EXPORT     __attribute__((visibility("default")))
#  define Q_DECL_IMPORT     __attribute__((visibility("default")))
#endif

#if defined(FLOOR_CALIBRATION_DLL_LIBRARY)
#  define FLOOR_CALIBRATION_DLL_EXPORT Q_DECL_EXPORT
#else
#  define FLOOR_CALIBRATION_DLL_EXPORT Q_DECL_IMPORT
#endif

#ifdef __cplusplus
extern "C" {
#endif
    int FLOOR_CALIBRATION_DLL_EXPORT floor_calibration_c(unsigned char *img, float fx, float cx, float cy, double Hmat[]);
#ifdef __cplusplus
}
#endif

floor_calibration_c.cc

#include "floor_calibration_c.h"
#include "floor_calibration.h"

int floor_calibration_c(unsigned char *img, float fx, float cx, float cy, double Hmat[]){
   return floor_calibration(img, fx, cx, cy, Hmat);
}

编译

  1. cmake -B build .
  2. cmake --build build --config Release

编译结果:
image

新库中的符号:
image

原始库中的符号:
image

posted @   周文靖  阅读(192)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示