简体   繁体   中英

How to add compile options to CMake FetchContent dependency using target interface

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

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}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM