Skip to content

Instantly share code, notes, and snippets.

@dberzano
Created January 28, 2015 11:11
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dberzano/8194ddfc9b8fbd5529ae to your computer and use it in GitHub Desktop.
Save dberzano/8194ddfc9b8fbd5529ae to your computer and use it in GitHub Desktop.
CMake: how to use optional arguments in macros and how to escape/unescape args to a shell
cmake_minimum_required(VERSION 2.8)
project(testoptargsandescape)
macro(testmacro testarg1 testarg2)
message(STATUS "testarg1 = \"${testarg1}\"")
message(STATUS "testarg2 = \"${testarg2}\"")
message(STATUS "Optional arg = \"${ARGV2}\"")
#if(${ARGV2}) # <-- this DOES NOT work
# ARGN is not a variable: assign its value to a variable
set(ExtraMacroArgs ${ARGN})
# Get the length of the list
list(LENGTH ExtraMacroArgs NumExtraMacroArgs)
# Execute the following block only if the length is > 0
if(NumExtraMacroArgs GREATER 0)
message(STATUS ">>> First optional arg = \"${ARGV2}\"")
foreach(ExtraArg ${ExtraMacroArgs})
message(STATUS ">>> Element of list of opt args = ${ExtraArg}")
endforeach()
endif()
endmacro(testmacro)
#
# Here we test string splitting
#
# This is a string escaped for a Unix shell
set(StringToSplit "-DLinux -DDATE_SYS=Linux -Dlong32=\"int\" -Dlong64=\"long long\" -DdatePointer=\"long\" -I/date/rorc -I/date/runControl -I/date/readList -I/date/eventBuilder -I/date/banksManager -I/date/bufferManager -I/date/db -I/date/commonDefs -I/date/monitoring -I/date/infoLogger -I/date/logbook")
# Print it
message(STATUS "Original String: ${StringToSplit}")
# Separate it to a list, as if a Unix shell would do
separate_arguments(SplitList UNIX_COMMAND ${StringToSplit})
# Print each element of the list
foreach(SplitListItem ${SplitList})
message(STATUS "Split Item: ${SplitListItem}")
endforeach()
# This external command prints each element received: the command is executed
# immediately by CMake.
# NOTE: we need to pass ${SplitList} WITHOUT quotes!
execute_process(COMMAND /tmp/test2/cmd.sh ${SplitList})
# Same story here: we need to pass ${SplitList} WITHOUT quotes!
# The command is executed upon invoking "make testescape"
add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/cmd.out"
COMMAND /tmp/test2/cmd.sh
ARGS ${SplitList}
)
add_custom_target(testescape DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/cmd.out")
# Invoking these macros tests optional arguments
testmacro("pipo1" "pipo2")
testmacro("pipo3" "pipo4" "pipo5")
testmacro("pipo3" "pipo4" "pipo5" "pipo 6 with space")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment