背景
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);
}
编译
- cmake -B build .
- cmake --build build --config Release
编译结果:
新库中的符号:
原始库中的符号: