Propagating CXX flags to out of source projects?

I need to propagate some cross-compiler flags like -mcpu down to some lower level libraries that are out of source. Is there “CMake way” to do this or do I need to agree upon some global variable name convention and “pass” the flags that way? For example…

In source

proj/source/CMakeLists.txt
set(global_cxx_flags -mcpu=cortex-m4)
add_directory(…/…/somelib somelib EXCLUDE_FROM_ALL)

Out of source …/…/somelib/CMakeLists.txt

target_compile_options(somelib
PRIVATE ${global_cxx_flags}
)

Seems icky.

add_compile_options

https://cmake.org/cmake/help/latest/command/add_compile_options.html?highlight=add_compile_options

This is what I use to propagate compiler flags like /Zi and /MP in our drivers.

Supports generator expressions, uses properties, etc.

2 Likes

Is this what you wanted?

Btw please only use add_compile_definitions if you are the top level project. Otherwise projects that absorb you may have to go through unnecessary hurdles.

Oh I totally get that. I just don’t know how to deal out of source projects. I can’t rearrange the dir structure.

No. I’ve read that page many times and it works great for subdirs of my project. It does not work for out of source builds. That is my question, how to push flags to out of source builds which I admit is odd but I cannot change the dir structure for this build.

Has something failed with CXX flags when using add_subdirectory()? I don’t recall having any issues with add_subdirectory(src_dir bin_dir) and src_dir wasn’t in the same directory as the top-level source directory; and this was with using toolchains and cross-compiling. In general you wouldn’t expect to have to do anything special. How do you define the CXX flags? As part of CMAKE_CXX_FLAGS_INIT?

add_subdirectory() works fine. add_compile_definitions(), however, does not propagate to out-of-source dirs added via add_subdirectory() as far as I can tell. I try not to touch any CMAKE_xxx variables.

Again, assume this dir structure where some_other_proj and some_proj are peers.
some_other_proj
\_ source
some_proj
\_ source (CMakeLists.txt)

Like I said this works for me in CMake 3.16. I’ve tested both add_compile_definitions() and add_compile_options(). Both of these propagate correctly when using add_subdirectory(../src2 src2). The command I use when running CMake is cmake -S src1 -B test_build. Where src1 and src2 are at the same directory level.

$ cat src1/CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(ProjectName)

#add_compile_definitions(testflag1)
add_compile_options(-Dtestflag1)
add_subdirectory(../src2 src2)
add_executable(exe_test file1.c)
target_link_libraries(exe_test lib2)

Okay, thank you for forcing me to re-read what I wrote in my CMakeLists.txt. I, of course, was wrong. I was using target_compile_definitions()!

Good to know I wasn’t going insane, Mark would you mind marking my answer as correct?

Oops sorry. Done. Thanks again for your help.