为什么 cmake 在不应该显示消息时显示消息?

Why cmake shows message when it should not?

找到了fltk,但是测试没有通过,为什么?

定义一个简单的宏

macro(assert TEST COMMENT)
  message(${TEST})
  if(NOT ${TEST})
    message("Assertion failed: ${COMMENT}")
  endif()
endmacro()

# use the macro
find_library(FLTK_LIB fltk)
assert(${FLTK_LIB} "Unable to find library fltk")

输出:

/usr/lib/x86_64-linux-gnu/libfltk.so
Assertion failed: Unable to find library fltk
if( NOT ${TEST} )

你在这里展开TEST,也就是说你基本上是在说...

if( NOT "/usr/lib/x86_64-linux-gnu/libfltk.so" )

CMake docs on if 说明:

if(<string>)

A quoted string always evaluates to false unless:

  • The string's value is one of the true constants [...]

所以默认为false,true常量为:

[...] 1, ON, YES, TRUE, Y, or a non-zero number.

你的字符串两者都不是,所以它是假的,所以你的断言总是触发。

如果你在function,解决方案就是写...

if( NOT TEST )

...因为那不会测试字符串,而是测试文档说明的变量...

if(<variable>)

True if given a variable that is defined to a value that is not a false constant. False otherwise, including if the variable is undefined.

因此默认值为真,除非您的变量未定义或为假常量之一...

0, OFF, NO, FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in the suffix -NOTFOUND

不幸的是,您将断言编写为宏,而不是函数。不幸的是,因为...

Note that macro arguments are not variables.

在这一点上,我个人注意到我的 C/C++ 程序员基因“宏是邪恶的”,并建议您将 assert() 变成 function 并编写 if( NOT TEST ).