Define new variable in cmake configure script

Hi,

Let suppose I have a file called myconf.cmake.in and inside it I have:

set(MY_VAR ${CMAKE_SOURCE_DIR}) 

message(CMAKE_SOURCE_DIR: ${CMAKE_SOURCE_DIR})
message(MY_VAR: ${MY_VAR})

After doing configure_file(${CMAKE_SOURCE_DIR}/myconf.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/myconf.cmake) I can open configured myconf.cmake and I can see that CMAKE_SOURCE_DIR is set to a source dir (as it was expected) while MY_VAR is empty (unexpected for me).

Thus I think I have some problems when defining new variables in cmake configuring scripts.
Is there a way to overcome this?

cmake 3.19.2

Did you call configure_file() before or after setting MY_VAR? You should set the variable first, then call configure_file().

1 Like

If I understand correctly, you want to do:

configure_file(${CMAKE_SOURCE_DIR}/myconf.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/myconf.cmake @ONLY)

And:

set(MY_VAR @CMAKE_SOURCE_DIR@) 

message(CMAKE_SOURCE_DIR: @CMAKE_SOURCE_DIR@)
message(MY_VAR: ${MY_VAR})
1 Like

Actually I want to set MY_VAR inside configuring script.

I think this is the same that I did. I just tried and I get:

message(MY_VAR: )

MY_VAR is empty

Ah, I get it now. Yes, @fenrir’s suggestion is correct.

1 Like

Did you add the @ONLY argument to the configure_file invocation?

Edit:
Apparently now you did :wink:

1 Like

Yeah, the @ONLY argument is important here. Otherwise, ${MY_VAR} gets replaced with the value of ${MY_VAR} from the calling script, which in this case is empty because it hasn’t been set.

1 Like

@fenrir, @kyle.edwards thank you!
You were right.

Without @ONLY argument in configure_file() cmake tries to replace MY_VAR with the value of MY_VAR in assumption that it was previously set in my project. But it wasnt in my case and it set to an empty (I didn’t think about that)

So I needed to add @ONLY argument and make difference between ${MY_VAR} and @MY_VAR@ in configuration script

Thank you very much!