本篇文章给大家分享《使用 QT 创建共享 C 库》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。
我正在尝试使用 qt 创建一个共享(动态)c++ 库,但是在要使用该库的客户端应用程序中,不会链接任何 qt 库。
我按照有关 qt 的教程创建了一个 pro 文件和头文件,如下例所示。
专业文件:
qt -= gui
template = lib
config += dynamiclib
config += c++11
# the following define makes your compiler emit warnings if you use
# any qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). please consult the documentation of the
# deprecated api in order to know how to port your code away from it.
defines += qt_deprecated_warnings, maitschsdk_library
# you can also make your code fail to compile if it uses deprecated apis.
# in order to do so, uncomment the following line.
# you can also select to disable deprecated apis only up to a certain version of qt.
#defines += qt_disable_deprecated_before=0x060000 # disables all the apis deprecated before qt 6.0.0
sources += \
maitchsdk.cpp
headers += \
maitchsdk.h
# default rules for deployment.
unix {
target.path = $$[qt_install_plugins]/generic
}
!isempty(target.path): installs += target
头文件:
#ifndef MAITCHSDK_H
#define MAITCHSDK_H
#include <QtCore/QtGlobal>
#if defined(MAITSCHSDK_LIBRARY)
# define MAITSCHSDK_EXPORT Q_DECL_EXPORT
#else
# define MAITSCHSDK_EXPORT Q_DECL_IMPORT
#endif
class MAITSCHSDK_EXPORT MAItchSDK
{
public:
MAITSCHSDK_EXPORT MAItchSDK(const char *glimpseIp,int glimpsePort,const char *itchIp,int itchPort);
};
#endif // MAITCHSDK_H
但是当我这样实现时,头文件包含 qt 依赖项,因此客户端应用程序也需要具有此依赖项,这不是我们想要的。 我的另一个要求是,这个库也可以用 golang 调用(通过使用 cgo),所以我需要使用一些 extern "c" 方法为这个库项目创建一个 c 包装器,我'我浏览了所有文档和教程,但无法找到合适的解决方案。
有人知道如何使用 qt 创建基本的 c 共享库吗?
谢谢
解决方案
要消除对 Qt 的依赖,您必须确保您的标头不 #include 任何 Qt 标头。
就您而言,您有 #include <QtCore/QtGlobal>,它用于跨平台宏 Q_DECL_IMPORT/Q_DECL_EXPORT。从标头中删除这些宏,并将跨平台宏替换为特定于平台的版本(例如 Q_DECL_IMPORT -> __declspec(dllimport) for Windows)
这是一个与上述问题完全不同的问题。
Qt 本身并不关心您是否在代码中使用 extern "C" 。因此,首先专注于构建不依赖 Qt 的“普通 C++”DLL。
成功后,您无需再更改 *.pro 文件。只需使用 extern "C" { ... } 将所有导出的函数包装在标头中即可。有关简单示例,请参阅 https://learn.microsoft.com/en-us/cpp/build/exporting-c-functions-for-use-in-c-or-cpp-language-executables?view=vs-2019。
此外,请参阅此 StackOverflow 答案,了解使用 extern "C" 时必须遵循的限制:extern "C" with class and DLL
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《使用 QT 创建共享 C 库》文章吧,也可关注golang学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
