unblocker
unblocker

Reputation: 51

cmake extract substring from variable

I have variable CC_OPTIONS has value set like below

-arch arm64 -mcpu=abc1 -c --debug -O2 -static -fstack-protector -ffreestanding -nostartfiles -std=c11

I wanted to extract -mcpu=abc1 from CC_OPTIONS

Tried below approach, but getting more than what i wanted.

string(REGEX REPLACE ".*mcpu=(.*)\ .*" "\\1" CPU_TYPE "${CC_OPTIONS}")

any suggestions?

Upvotes: 3

Views: 6261

Answers (2)

fabian
fabian

Reputation: 82461

If you use if(MATCHES) you can get character groups of the match using CMAKE_MATCH_<n>

set(MY_VAR "-arch arm64 -mcpu=abc1 -c --debug -O2 -static -fstack-protector -ffreestanding -nostartfiles -std=c11")

if (MY_VAR MATCHES "^([^ ]+ +)*(-mcpu=[^ ]+)( +[^ ]+)*$")
    message(STATUS "Found match: ${CMAKE_MATCH_2}")
else()
    message(FATAL_ERROR "mismatch")
endif()

Upvotes: 2

Arkadiusz Drabczyk
Arkadiusz Drabczyk

Reputation: 12393

Like that:

cmake_minimum_required (VERSION 2.8.11)
project (HELLO)
set(CC_OPTIONS "-arch arm64 -mcpu=abc1 -c --debug -O2 -static -fstack-protector -ffreestanding -nostartfiles -std=c11")
message(${CC_OPTIONS})

string(REGEX MATCH "\\-mcpu=[^ $]+" CPU_TYPE ${CC_OPTIONS})
message(${CPU_TYPE})

Example:

$ cmake .
-arch arm64 -mcpu=abc1 -c --debug -O2 -static -fstack-protector -ffreestanding -nostartfiles -std=c11
-mcpu=abc1
-- Configuring done
-- Generating done
-- Build files have been written to: /home/ja/cmake

Upvotes: 3

Related Questions