来自非 C++ 背景,我正在尝试使用 Qt 重写一些项目。我需要创建一个共享库来容纳常用的“实用程序”功能。我不需要一个类,因为所有函数都是静态的,所以我的想法是创建一个包含所有函数的命名空间,但是,使用 Qt 提供的共享库模板来完成这个是行不通的。这可能吗?如果是这样,有人可以指出我正确的方向吗?
例如,我想将下面的 Utils 函数放入一个共享库中,这样我就不必将文件复制到我要使用它们的所有项目中。
Utils.h
#ifndef UTILS_H
#define UTILS_H
#include <QtCore>
#include <QString>
#include <QDateTime>
#include <QFileInfo>
namespace Utils {
QString getAppName();
bool stringToBool(const QString &str);
QString getFileTimeStamp();
QString getPacketTime();
QString getTodayStamp();
}
#endif // UTILS_H
Utils.cpp
#include <Helpers/utils.h>
namespace Utils {
QString getAppName()
{
return QFileInfo(QCoreApplication::applicationFilePath()).baseName();
}
bool stringToBool(const QString &str)
{
return str.contains("1");
}
QString getFileTimeStamp()
{
return QDateTime::currentDateTime().toString("ddhhmmsszzz");
}
QString getPacketTime()
{
return QDateTime::currentDateTime().toString("hh:mm:ss");
}
QString getTodayStamp()
{
return QDateTime::currentDateTime().toString("MMddyy");
}
}
最佳答案
除了标题中的不幸包含之外,这在代码方面看起来还不错。
如果您将其构建为共享库并且平台使用符号隐藏,那么您需要“导出”函数。
这通常是通过具有“导出宏” header 来完成的,即像这样的东西
#include <qglobal.h>
#ifndef UTILS_EXPORT
# if defined(MAKE_UTILS_LIB)
/* We are building this library */
# define UTILS_EXPORT Q_DECL_EXPORT
# else
/* We are using this library */
# define UTILS_EXPORT Q_DECL_IMPORT
# endif
#endif
然后用于标记在链接时应该可见的符号
#include "utils_export.h"
namespace Utils {
UTILS_EXPORT QString getAppName();
}
库的.pro
文件需要设置触发宏导出部分的define
DEFINES += MAKE_UTILS_LIB=1
关于c++ - Qt - 包含 'Utility' 函数的共享库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40050767/