8

I have a dependency included using CMake's FetchContent that needs to be built using some build flag (cmake -DFLAG=ON).

This question is also asked in here and the provided answer seems to be to set a variable on the current scope using set. For instance set(FLAG ON).

My question: Is there a way to achieve the same, without polluting the scope?

I have tried using set_target_properties or target_compile_options without success. If I call these after FetchContent_MakeAvailable they have no effect and if I call them before then the target does not exists and it throws an error.

include(FetchContent)
FetchContent_Declare(
    Dependency
    GIT_REPOSITORY ...
    GIT_TAG ...
)

set(FLAG ON) # This works, but pollutes the scope. I only want this flag to take effect on "Dependency"

# set_target_properties(Dependency PROPERTIES FLAG ON) # This won't work (error)
# target_compile_options(Dependency PUBLIC -DFLAG=ON) # This won't work either (error)

FetchContent_MakeAvailable(Dependency)

# set_target_properties(Dependency PROPERTIES FLAG ON) # This has no effect
# target_compile_options(Dependency PUBLIC -DFLAG=ON) # This has no effect
1
  • 1
    Just set() the variable before FetchContent_MakeAvailable call and unset() it after the call. Commented Sep 28, 2022 at 17:32

1 Answer 1

7

I don't know if this should be an answer or a comment, but you could use the following pattern to not pollute scope:

set(CMAKE_CXX_FLAGS_OLD "${CMAKE_CXX_FLAGS}")

# Add other flags here.
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-restrict")

FetchContent_MakeAvailable(gflags)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS_OLD}")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.