Search code examples
cmaketext-processinguname

How to strip trailing whitespace in CMake variable?


We are trying to improve the makefiles produced by CMake. For Clang, GCC and ICC, we want to add -march=native. The block to do so looks like:

# -march=native for GCC, Clang and ICC on i386, i486, i586, i686 and x86_64.
message(STATUS, "1")
message(STATUS, "Compiler: x${CMAKE_CXX_COMPILER_ID}x")
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" OR "${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Intel")
    message(STATUS, "2")
    message(STATUS, "Machine: x${UNAME_MACHINE}x")
    if (("${UNAME_MACHINE}" MATCHES "i.86") OR ("${UNAME_MACHINE}" STREQUAL "x86_64"))
            message(STATUS, "3")
        if (CMAKE_VERSION VERSION_LESS 2.8.12)
            add_definitions(-march=native)
        else()
            add_compile_options(-march=native)
        endif()
    endif()
endif()

The messages statements show the machine string from uname has a trailing newline:

STATUS,1
STATUS,Compiler: xGNUx
STATUS,2
STATUS,Machine: xx86_64
x

The block to produce UNAME_MACHINE is:

# We need the output 'uname -m' for Unix and Linux platform detection
#    Be prepared for i386-i686, amd64, x86_64, arm, arm64, armel, armhf,
#    mips, mips64, aarch32 and aarch64 (for starters)
set (UNAME_CMD "uname")
set (UNAME_ARG "-m")
execute_process(COMMAND ${UNAME_CMD} ${UNAME_ARG}
    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
    RESULT_VARIABLE UNAME_RESULT
    OUTPUT_VARIABLE UNAME_MACHINE)

How do I strip the trailing newline from UNAME_MACHINE in CMake?

Or should I switch to a regex matches, which should not be affected by the newline?

Or, should I do something else?


We are attempting to support CMake 2.8 through Current. That roughly takes us back to Ubuntu 12.04 LTS. There are some other operating systems around that time that push things back a little further. While string(STRIP <string> <output variable>) looks promising, CMake does not supply version information with its documentation, so we are not sure if it will meet requirements.

EDIT it appears stripping does not work in 3.0.2, so it appears we need something else.

# Strip lead and trailing whitepasce
string(STRIP UNAME_MACHINE, UNAME_MACHINE)

Results in the following (we expect xx86_64x):

STATUS,1
STATUS,Compiler: xGNUx
STATUS,2
STATUS,Machine: xUNAME_MACHINE,x

Adding dollar sign and curly braces, ${UNAME_MACHINE}, results in the same original problem (the newline is still present).


Solution

  • This strips terminating newline in the variable <varname>:

    string(REGEX REPLACE "\n$" "" <varname> "${<varname>}")
    

    Works for one of the project I involved to since CMake 2.8.