测试函数

Test functions return a boolean value that you can test for in the conditional parts of scopes. Test functions can be divided into built-in functions and function libraries.

另请参阅 替换函数 .

内置测试函数

Basic test functions are implemented as built-in functions.

cache(variablename, [set|add|sub] [transient] [super|stash], [source variablename])

This is an internal function that you will typically not need.

CONFIG(config)

This function can be used to test for variables placed into the CONFIG variable. This is the same as scopes, but has the added advantage that a second parameter can be passed to test for the active config. As the order of values is important in CONFIG variables (that is, the last one set will be considered the active config for mutually exclusive values) a second parameter can be used to specify a set of values to consider. For example:

CONFIG = debug
CONFIG += release
CONFIG(release, debug|release):message(Release build!) #will print
CONFIG(debug, debug|release):message(Debug build!) #no print
					

Because release is considered the active setting (for feature parsing) it will be the CONFIG used to generate the build file. In the common case a second parameter is not needed, but for specific mutual exclusive tests it is invaluable.

contains(variablename, value)

成功若变量 variablename contains the value value ; otherwise fails. It is possible to specify a regular expression for parameter value .

You can check the return value of this function using a scope.

例如:

contains( drivers, network ) {
    # drivers contains 'network'
    message( "Configuring for network build..." )
    HEADERS += network.h
    SOURCES += network.cpp
}
					

The contents of the scope are only processed if the drivers variable contains the value network . If this is the case, the appropriate files are added to the SOURCES and HEADERS 变量。

count(variablename, number)

成功若变量 variablename contains a list with the specified 编号 of values; otherwise fails.

This function is used to ensure that declarations inside a scope are only processed if the variable contains the correct number of values. For example:

options = $$find(CONFIG, "debug") $$find(CONFIG, "release")
count(options, 2) {
    message(Both release and debug specified.)
}
					

debug(level, message)

Checks whether qmake runs at the specified debug level. If yes, it returns true and prints a debug message.

defined(name[, type])

Tests whether the function or variable 名称 is defined. If type is omitted, checks all functions. To check only variables or particular type of functions, specify type . It can have the following values:

  • test only checks test functions
  • replace only checks replace functions
  • var only checks variables

equals(variablename, value)

Tests whether variablename equals the string value .

例如:

TARGET = helloworld
equals(TARGET, "helloworld") {
    message("The target assignment was successful.")
}
					

error(string)

This function never returns a value. qmake displays string as an error message to the user and exits. This function should only be used for unrecoverable errors.

例如:

error(An error has occurred in the configuration process.)
					

eval(string)

Evaluates the contents of the string using qmake syntax rules and returns true. Definitions and assignments can be used in the string to modify the values of existing variables or create new definitions.

例如:

eval(TARGET = myapp) {
    message($$TARGET)
}
					

注意: Quotation marks can be used to delimit the string, and the return value can be discarded if it is not needed.

exists(filename)

Tests whether a file with the given filename exists. If the file exists, the function succeeds; otherwise it fails. If a regular expression is specified for the filename, this function succeeds if any file matches the regular expression specified.

例如:

exists( $(QTDIR)/lib/libqt-mt* ) {
      message( "Configuring for multi-threaded Qt..." )
      CONFIG += thread
}
					

注意: "/" should be used as a directory separator, regardless of the platform in use.

export(variablename)

Exports the current value of variablename from the local context of a function to the global context.

for(iterate, list)

Starts a loop that iterates over all values in list , setting iterate to each value in turn. As a convenience, if list is 1..10 then iterate will iterate over the values 1 through 10.

例如:

LIST = 1 2 3
for(a, LIST):exists(file.$${a}):message(I see a file.$${a}!)
					

greaterThan(variablename, value)

Tests that the value of variablename 大于 value . First, this function attempts a numerical comparison. If at least one of the operands fails to convert, this function does a string comparison.

例如:

ANSWER = 42
greaterThan(ANSWER, 1) {
    message("The answer might be correct.")
}
					

It is impossible to compare two numbers as strings directly. As a workaround, construct temporary values with a non-numeric prefix and compare these.

例如:

VALUE = 123
TMP_VALUE = x$$VALUE
greaterThan(TMP_VALUE, x456): message("Condition may be true.")
					

另请参阅 lessThan() .

if(condition)

Evaluates 条件 . It is used to group boolean expressions.

例如:

if(linux-g++*|macx-g++*):CONFIG(debug, debug|release) {
    message("We are on Linux or Mac OS, and we are in debug mode.")
}
					

include(filename)

Includes the contents of the file specified by filename into the current project at the point where it is included. This function succeeds if filename is included; otherwise it fails. The included file is processed immediately.

You can check whether the file was included by using this function as the condition for a scope. For example:

include( shared.pri )
OPTIONS = standard custom
!include( options.pri ) {
    message( "No custom build options specified" )
OPTIONS -= custom
}
					

infile(filename, var, val)

Succeeds if the file filename (when parsed by qmake itself) contains the variable var 采用值 val ; otherwise fails. If you do not specify val , the function tests whether var has been assigned in the file.

isActiveConfig

This is an alias for the CONFIG 函数。

isEmpty(variablename)

成功若变量 variablename is empty; otherwise fails. This is the equivalent of count( variablename, 0 ) .

例如:

isEmpty( CONFIG ) {
CONFIG += warn_on debug
}
					

isEqual

This is an alias for the 等于 函数。

lessThan(variablename, value)

Tests that the value of variablename 小于 value . Works as greaterThan() .

例如:

ANSWER = 42
lessThan(ANSWER, 1) {
    message("The answer might be wrong.")
}
					

load(feature)

Loads the feature file ( .prf ) specified by feature , unless the feature has already been loaded.

log(message)

Prints a message on the console. Unlike the message function, neither prepends text nor appends a line break.

另请参阅 message() .

message(string)

Always succeeds, and displays string as a general message to the user. Unlike the error() function, this function allows processing to continue.

message( "This is a message" )
					

The above line causes "This is a message" to be written to the console. The use of quotation marks is optional, but recommended.

注意: By default, messages are written out for each Makefile generated by qmake for a given project. If you want to ensure that messages only appear once for each project, test the build_pass variable in conjunction with a scope to filter out messages during builds. For example:

!build_pass:message( "This is a message" )
					

mkpath(dirPath)

Creates the directory path dirPath . This function is a wrapper around the QDir::makepath function.

requires(condition)

Evaluates 条件 . If the condition is false, qmake skips this project (and its SUBDIRS ) when building.

注意: 还可以使用 REQUIRES variable for this purpose. However, we recommend using this function, instead.

system(command)

Executes the given 命令 in a secondary shell. Succeeds if the command returns with a zero exit status; otherwise fails. You can check the return value of this function using a scope.

例如:

system("ls /bin"): HAS_BIN = TRUE
					

See also the replace variant of system() .

touch(filename, reference_filename)

Updates the time stamp of filename to match the time stamp of reference_filename .

unset(variablename)

移除 variablename from the current context.

例如:

NARF = zort
unset(NARF)
!defined(NARF, var) {
    message("NARF is not defined.")
}
					

versionAtLeast(variablename, versionNumber)

Tests that the version number from variablename >= versionNumber . The version number is considered to be a sequence of non-negative decimal numbers delimited by '.'; any non-numerical tail of the string will be ignored. Comparison is performed segment-wise from left to right; if one version is a prefix of the other, it is considered smaller.

versionAtMost(variablename, versionNumber)

Tests that the version number from variablename <= versionNumber . Works as versionAtLeast() .

warning(string)

Always succeeds, and displays string as a warning message to the user.

write_file(filename, [variablename, [mode]])

Writes the values of variablename to a file with the name filename , each value on a separate line. If variablename is not specified, creates an empty file. If mode is append and the file already exists, appends to it instead of replacing it.

测试函数库

Complex test functions are implemented in a library of .prf files.

packagesExist(packages)

Uses the PKGCONFIG mechanism to determine whether or not the given packages exist at the time of project parsing.

This can be useful to optionally enable or disable features. For example:

packagesExist(sqlite3 QtNetwork QtDeclarative) {
    DEFINES += USE_FANCY_UI
}
					

And then, in the code:

#ifdef USE_FANCY_UI
    // Use the fancy UI, as we have extra packages available
#endif
					

prepareRecursiveTarget(target)

Facilitates the creation of project-wide targets similar to the 安装 target by preparing a target that iterates through all subdirectories. For example:

TEMPLATE = subdirs
SUBDIRS = one two three
prepareRecursiveTarget(check)
					

Subdirs that have have_no_default or no_<target>_target specified in their .CONFIG are excluded from this target:

two.CONFIG += no_check_target
					

You must add the prepared target manually to QMAKE_EXTRA_TARGETS :

QMAKE_EXTRA_TARGETS += check
					

To make the target global, the code above needs to be included into every subdirs subproject. In addition, to make these targets do anything, non-subdirs subprojects need to include respective code. The easiest way to achieve this is creating a custom feature file. For example:

# <project root>/features/mycheck.prf
equals(TEMPLATE, subdirs) {
    prepareRecursiveTarget(check)
} else {
    check.commands = echo hello user
}
QMAKE_EXTRA_TARGETS += check
					

The feature file needs to be injected into each subproject, for example by .qmake.conf:

# <project root>/.qmake.conf
CONFIG += mycheck
					

qtCompileTest(test)

Builds a test project. If the test passes, true is returned and config_<test> is added to the CONFIG variable. Otherwise, false is returned.

To make this function available, you need to load the respective feature file:

# <project root>/project.pro
load(configure)
					

This also sets the variable QMAKE_CONFIG_TESTS_DIR to the config.tests subdirectory of the project's parent directory. It is possible to override this value after loading the feature file.

Inside the tests directory, there has to be one subdirectory per test that contains a simple qmake project. The following code snippet illustrates the .pro file of the project:

# <project root>/config.tests/test/test.pro
SOURCES = main.cpp
LIBS += -ltheFeature
# Note that the test project is built without Qt by default.
					

The following code snippet illustrates the main .cpp file of the project:

// <project root>/config.tests/test/main.cpp
#include <TheFeature/MainHeader.h>
int main() { return featureFunction(); }
					

The following code snippet shows the invocation of the test:

# <project root>/project.pro
qtCompileTest(test)
					

If the test project is built successfully, the test passes.

The test results are automatically cached, which also makes them available to all subprojects. It is therefore recommended to run all configuration tests in the top-level project file.

To suppress the re-use of cached results, pass CONFIG+=recheck to qmake.

另请参阅 load() .

qtHaveModule(name)

Checks whether the Qt module specified by 名称 is present. For a list of possible values, see QT .