Qt - 包含'实用程序'的共享库功能?

时间:2016-10-14 19:34:15

标签: c++ qt utilities

来自非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");
    }

}

1 个答案:

答案 0 :(得分:2)

除了标题中的不幸内容之外,这看起来还不错。

如果您将其构建为共享库并且平台使用符号隐藏,那么您需要&#34; export&#34;功能。

这通常是通过使用&#34;导出宏来实现的。标题,即类似的东西

#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