c++qtutilities

Qt - Shared Library Containing 'Utility' Functions?


Coming from non C++ background, I am trying to rewrite a few projects using Qt. I need to create a shared library that will house commonly used 'utility' functions. I do not need a class as all functions will be static so my thinking was to create a namespace that will contain all the functions however, accomplishing this using the Qt provided shared library template is not working. Is this possible? If so, can someone please point me in the right direction?

For example, I want to take the Utils functions below and put them into a shared library so that I do not have to copy the files into all projects where I want to use them.

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

}

Solution

  • Aside from unfortunate includes in the header this looks OK code wise.

    If you are building this as a shared library and the platform uses symbol hiding, then you need to "export" the functions.

    This is usually done by having an "export macro" header, i.e. something like this

    #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
    

    That is then being used to mark the symbols that should be visible at link time

    #include "utils_export.h"
    
    namespace Utils {
        UTILS_EXPORT QString getAppName();
    }
    

    The library's .pro file needs to set the define that triggers the export part of the macro

    DEFINES += MAKE_UTILS_LIB=1