如何将哈希字符 (#) 添加到 qmake 变量

How to add a hash character (#) to a qmake variable

我想用 qmake 写一个配置文件,#define 有几个值。但我不能简单地创建包含井号或井号字符 (#) 的变量。非工作示例:

lines = "/* Autogenerated: do not edit */"
if(foo): lines += "#define MYLIB_WITH_FOO 1"
else:    lines += "#define MYLIB_WITH_FOO 0"
write_file(config.h, lines)

散列开始评论(在字符串内!),所以这是行不通的。如何在 qmake 下为 write_file 生成正确的 #defines?

诀窍是使用 $$system() 创建散列字符。此示例适用于 Windows 和 Linux:

pound = $$system(printf $$system_quote())
if(foo): lines += "$${pound}define MYLIB_WITH_FOO 1"
else:    lines += "$${pound}define MYLIB_WITH_FOO 0"

通常在 C 或 C++ 应用程序源中包含 "config.h" header,它是由构建系统从模板生成的(例如 "config.h.in")。这可以使用 autotools 和 CMake 获得 - 请参阅:configure_file()。但是 Qmake 呢?

这是使用 QMAKE_SUBSTITUTES. Another reference 的替代方法。

test.pro

TEMPLATE = app
QT = core
CONFIG += cmdline c++11
VERSION = 1.2.3
FOO = 1
QMAKE_SUBSTITUTES = config.h.in
SOURCES += main.cpp
DISTFILES += config.h.in

config.h.in

/* Autogenerated: do not edit */
#ifndef CONFIG_H
#define CONFIG_H

#define MYLIB_VERSION '"$$VERSION"'
#define MYLIB_BANNER '"Project version $$VERSION created with Qt $$QT_VERSION"'
#define MYLIB_WITH_FOO $$FOO

#endif // CONFIG_H

main.cpp

#include <QCoreApplication>
#include <QDebug>
#include "config.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    qDebug() << MYLIB_BANNER;
    if (MYLIB_WITH_FOO) {
        qDebug() << "Foo included!";
    }
    return 0;
}

输出:

Project version 1.2.3 created with Qt 5.12.5

Foo included!

有一个名为 LITERAL_HASH 的预定义变量专门用于处理此问题。

如果这个名称看起来太长,您可以创建一个自己的名称:

H = $$LITERAL_HASH
lines = "/* Autogenerated: do not edit */"
if(foo): lines += "$${H}define MYLIB_WITH_FOO 1"
else:    lines += "$${H}define MYLIB_WITH_FOO 0"
write_file(config.h, lines)