Setting `CMAKE_CXX_FLAGS` within a function

It seems that CMAKE_CXX_FLAGS isn’t being set when I set it inside of a function. I tried checking the contents, it is empty before and after, even within the same function.

These are all things I’ve tried, neither work for me:

set(${CMAKE_CXX_FLAGS} "${CMAKE_CXX_FLAGS} ${val}")
set(${CMAKE_CXX_FLAGS} "${${CMAKE_CXX_FLAGS}} ${val}")
set(${CMAKE_CXX_FLAGS} "${${CMAKE_CXX_FLAGS}} ${val}" PARENT_SCOPE)

You are wrong. To set a variable, use just the variable name, do not expand it:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${val}" PARENT_SCOPE)

Huh, when is the ${VAR} syntax used then?

When you pass variable name to a function:

function (UPDATE_MY_VAR my_var)
  set(${my_var} "my value" PARENT_SCOPE)
endfunction()

update_my_var(VAR_TO_UPDATE)
# here VAR_TO_UPDATE has value "my value"

Ah, okay. Also, is there a way of forwarding the scope of the variable above two or more functions?

No. You can only update variables of the parent scope.

Note that the better solution these days is something like:

add_library(buildflags INTERFACE)
target_compile_options(buildflags INTERFACE -Wsome-warning)

# For each target
target_link_libraries(mytgt PRIVATE buildflags)

@ben.boeckel You mean target_compile_options.

Indeed, thanks. I’ve updated the comment.