使用条件语句将 CMake 单元测试宏压缩为一个宏

Compacting CMake unit test macros into one macro using conditional statement

我想减少下面代码中的 CMake 宏调用,并将其压缩为一个 CMake 宏调用,以使用 if-else 语句执行我的操作。

我需要通过传递不同的高度和宽度参数来 运行 ctest(使用 CMake)。

请将此视为一些算术运算。

在我的例子中,根据宽度,我的高度范围会像这样改变:

  Width = 8 ,then height will be 8 16 24 
  Width = 16 ,then height will be 16 24 
  Width = 24 ,then height will be 24 32

那么,是否可以在 CMake 文件中使用一些 if-else 语句来对 EXECUTE_OPERATION(${width_val} ${height_val} ) 进行一次调用?

我当前的 CMake 文件如下所示:

set(width 8) 
set(size 8 16 24 )

foreach(size_val ${size}
  foreach(width_val  ${width})

  EXECUTE_OPEARTION(${width_val} ${height_val} )

  endforeach(width_val)
endforeach(size_val)

---------------------------

set(width 16) 
set(height 16 24 )

foreach(height_val ${height}
  foreach(width_val  ${width})

  EXECUTE_OPEARTION(${width_val} ${height_val} )

  endforeach(width_val)
endforeach(size_val)

---------------------------

set(width 24) 
set(size 24 32 )

foreach(size_val ${size}
  foreach(width_val  ${width})

  EXECUTE_OPEARTION(${width_val} ${height_val} )

  endforeach(width_val)
endforeach(size_val)

---------------------------

我尝试使用以下方法执行此操作,但没有成功:

set(width 8 16 24 ) 
 if(width == 8)
  set(height 8 16 24 )
 elif(width == 16)
  set(height 16 24 )
 elif(width == 24)
  set(height 24 32)

foreach(height_val ${height}
  foreach(width_val  ${width})

  EXECUTE_OPEARTION(${width_val} ${height_val} )

  endforeach(width_val)
endforeach(size_val)

您的 if 语句似乎具有 Python 语法。您应该使用 elseif 而不是 elif。此外,用于测试相等性的 CMake if 语句 syntaxEQUAL,而不是 ==

此外,您需要将 if 语句块 移动到 foreach() 中才能使其正常工作。尝试这样的事情:

# Define the width values to iterate through.
set(width 8 16 24)

# Iterate through each width value.
foreach(width_val ${width})
  # Set the height values, based on the current width value.
  if(${width_val} EQUAL 8)
    set(height 8 16 24)
  elseif(${width_val} EQUAL 16)
    set(height 16 24)
  elseif(${width_val} EQUAL 24)
    set(height 24 32)
  endif()

  # Loop through each height value.
  foreach(height_val ${height})
    message("Calling EXECUTE_OPEARTION() with args: Width: ${width_val}, Height: ${height_val}")
    EXECUTE_OPEARTION(${width_val} ${height_val})
  endforeach(height_val)
endforeach(width_val)

这将打印以下内容,验证是否使用正确的参数调用函数:

Calling EXECUTE_OPEARTION() with args: Width: 8, Height: 8
Calling EXECUTE_OPEARTION() with args: Width: 8, Height: 16
Calling EXECUTE_OPEARTION() with args: Width: 8, Height: 24
Calling EXECUTE_OPEARTION() with args: Width: 16, Height: 16
Calling EXECUTE_OPEARTION() with args: Width: 16, Height: 24
Calling EXECUTE_OPEARTION() with args: Width: 24, Height: 24
Calling EXECUTE_OPEARTION() with args: Width: 24, Height: 32