Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake list to string: simple semicolon replacement

Tags:

cmake

I am confused with a very simple example. I have a standard list, so basically its string representation uses semicolon as delimiters. I want to replace it by another one:

set(L1 "A" "B" "C")
message("L1: ${L1}")

string(REPLACE ";" "<->" L2 ${L1})
message("L2: ${L2}")

this snippet prints:

L1: A;B;C
L2: ABC

and I don't understand why. According to some other SO answers, my string replacement seems valid. What am I doing wrong ? Is there a way to store the value A<->B<->C in my 2nd variable ?

Note: I use CMake 3.7.2

like image 295
Antwane Avatar asked Mar 31 '17 09:03

Antwane


People also ask

How to replace a semicolon in a string with a regex?

The solution is to use a regex: I.e. only replace ; if it is preceded by a non- \ character (and put that character in the replacement). The almost works, but it doesn't handle the first empty element because the semicolon isn't preceded by anything. The final answer is to allow the start of string too:

How to create a list in CMake?

A list in cmake is a ; separated group of strings. To create a list the set command can be used. For example, set (var a b c d e) creates a list with a;b;c;d;e, and set (var "a b c d e") creates a string or a list with one item in it. (Note macro arguments are not variables, and therefore cannot be used in LIST commands.)

Why can't I start a string with a semicolon?

The almost works, but it doesn't handle the first empty element because the semicolon isn't preceded by anything. The final answer is to allow the start of string too: Oh and the \\ is because one level of escaping is removed by CMake processing the string literal, and another by the regex engine. You could also do this:


2 Answers

Just put ${L1} in quotes:

set(L1 "A" "B" "C")
message("L1: ${L1}")

string(REPLACE ";" "<->" L2 "${L1}")
message("L2: ${L2}")

Otherwise the list will be expanded again to a space separated parameter list.

Reference

  • cmake: when to quote variables?
like image 154
Florian Avatar answered Sep 23 '22 18:09

Florian


But ${L1} isn't a string, it's a list. If you want a string then you need to enclose it in double-quotes like "${L1}".

like image 40
Some programmer dude Avatar answered Sep 22 '22 18:09

Some programmer dude