0

How do I create a function (or macro) in cmake that adds to a list which is available in the outer scope? For instance, lets say I have a function (maybe it adds a new test):

function(AddToListFromFunction BinaryName OutVariable)
    set(OutVariable ${OutVariable} ${BinaryName} PARENT_SCOPE)
    message(STATUS "OutVariable ${OutVariable}" )
endfunction()
set(MyTests "")
AddToListFromFunction(MyBinary1 MyTests)
AddToListFromFunction(MyBinary2 MyTests)
message(STATUS "MyTests Variable:  ${MyTests}")

This outputs:

-- OutVariable MyTests
-- OutVariable MyTests
-- MyTests Variable:  

But what I expect it to output is:

-- OutVariable MyBinary1
-- OutVariable MyBinary1 MyBinary2
-- MyTests Variable:  MyBinary1 MyBinary2
CiaranWelsh
  • 7,014
  • 10
  • 53
  • 106
  • If you want to create variable with a name `MyTests` inside the function, then use `set(${OutVariable} ...)`. – Tsyvarev Oct 27 '20 at 12:18
  • Notice that my question is different from the one marked as duplicate, because I already have used `PARENT_SCOPE` – CiaranWelsh Oct 27 '20 at 12:20
  • @Tsyvarev This almost worked. The output I'm getting now is: `MyTests Variable: MyTests;MyBinary2`. I.e. the list is being overwritten each time insetad of added to. – CiaranWelsh Oct 27 '20 at 12:21
  • Okay, narrowed it down to `set(${OutVariable} "${${OutVariable}}" "${BinaryName}" PARENT_SCOPE)` but now I get an empty element in the list: `MyTests Variable: ;MyBinary1;MyBinary2`. Any suggestions for avoiding the empty first element? – CiaranWelsh Oct 27 '20 at 12:28
  • "Notice that my question is different from the one marked as duplicate, because I already have used PARENT_SCOPE" - Both your and the duplicate questions have a **purpose** to return a list from the function via output parameter. This is why I marked duplicate. Difference in *attempts* is not so important. As for the answer, you could perfectly add it to the answers for the **duplicate question**. This is a very intention of the "duplicate" mechanism on SO: answers for different (but duplicate) questions could be collected in a single place. – Tsyvarev Oct 27 '20 at 15:42
  • `you could perfectly add it to the answers for the duplicate question`. Good idea, I'll do that. – CiaranWelsh Oct 27 '20 at 20:23
  • Since you have provided an answer as the [answer post](https://stackoverflow.com/a/64562326/3440745) to the other question, you could remove an answer from the body of your question post: On Stack Overflow a question post shouldn't contain an answer. But providing in the **comment** a link to the post which helped you is perfectly valid, even if you wrote that post by yourself. – Tsyvarev Oct 27 '20 at 21:34

0 Answers0