Qt, linux, adding build date and time define

Viewed 2167

I'm trying to get the build date and time into my application so I can display in the about page.

In my pro file I have:

    DEFINES += "BUILDDATE=$$system(date +'%d-%m-%y %T')"

I've tried the date command with the format in a terminal on the system and it works fine.

In my source:

    QString strBldDate(BUILDDATE);

This all builds without error, when I check in the debugger, strBldDate is empty.

From discussions I've been told I can use message() in the ".pro" file to show for example:

    message($$system(date +"'%d-%m-%y %T'"))

This works and when I build I get something like:

    Project MESSAGE: 26-06-19 10:34:59

But how can I use the same to validate the contents of a definition?

    message(BUILDDATE)

After my above efforts just results in:

    Project MESSAGE: BUILDDATE
1 Answers

You actually could just use standard predefined macros for this in GCC and in MSVC.

Here is a list of predef macros in GCC: 3.7.1 Standard Predefined Macros

And for MSVC: Predefined Macros

Code could look something like this:

QString datetime = QStringLiteral(__DATE__) + QStringLiteral(" ") + QStringLiteral(__TIME__);

If you can't use predefined macros, just don't use empty spaces in definitions and pack it with backslash quote like this:

DEFINES += BUILDDATE=\\\"$$system( date "+%d.%m.%Y_%H:%M:%S" )\\\"

strBldDate.replace(QChar('_'), QChar(' '));

EDIT: Create builddatetime.h file and include it everywhere you need your build version:

#ifndef BUILDDATETIME_H
#define BUILDDATETIME_H

#include <QString>
const QString BUILDV =  QStringLiteral(__DATE__ " " __TIME__);

#endif // BUILDDATETIME_H

In your .pro file add builddatetime.h to headers (HEADERS += builddatetime.h) And the following lines:

buildtimeTarget.target = builddatetime.h
buildtimeTarget.depends = FORCE
buildtimeTarget.commands = touch $$PWD/builddatetime.h
PRE_TARGETDEPS += builddatetime.h
QMAKE_EXTRA_TARGETS += buildtimeTarget

This will touch builddatetime.h and all cpp files which include this header will be rebuild on each build and run command.

Related