c++ - Qt - 包含 'Utility' 函数的共享库?

标签 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");
    }

}

最佳答案

除了标题中的不幸包含之外,这在代码方面看起来还不错。

如果您将其构建为共享库并且平台使用符号隐藏,那么您需要“导出”函数。

这通常是通过具有“导出宏” 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/

相关文章:

c++ - 读取数据时如何处理不同版本的格式?

c++ - 打印没有nested_ptr的nested_exception

c++ - Qt QSqlDatabase 和 QSqlTableModel 与 PostgreSQL View 的兼容性?

qt - 从 qt 中的对话框打开新对话框

c++ - 使用 <filesystem> 检查目录是否存在

java - 我的 friend 说我的方法没用,有人能解释一下为什么吗?

c++ - 具有虚拟析构函数的派生类的 Sizeof

c++ - 从 switch block 返回时有什么性能差异?

c++ - QVariantList追加

visual-studio - VS 2008 或 2010 Express 版本是否附带任何可用的控制台 http 下载实用程序?