How to set_source_files_properties on top and use in sub?

Here is my project structure:

├── build
├── CMakeLists.txt
├── foo.cmake
├── src1.c
├── src2.c
├── sub1
│   ├── CMakeLists.txt
│   └── module_foo
│       └── CMakeLists.txt
└── sub2
    ├── CMakeLists.txt
    └── module_foo
        └── CMakeLists.txt
  • CMakeLists.txt:
cmake_minimum_required(VERSION 3.20.0)
set(CMAKE_VERBOSE_MAKEFILE ON)

project(top)

set(ROOTDIR ${CMAKE_CURRENT_LIST_DIR})
add_subdirectory(sub1)
add_subdirectory(sub2)
  • foo.cmake
add_library(src_${PROJECT_NAME}_foo INTERFACE)

if (${PROJECT_NAME} STREQUAL "sub1")
  target_sources(src_${PROJECT_NAME}_foo INTERFACE
    ${ROOTDIR}/src1.c
  )
elseif (${PROJECT_NAME} STREQUAL "sub2")
  target_sources(src_${PROJECT_NAME}_foo INTERFACE
    ${ROOTDIR}/src2.c
  )
endif()

get_target_property(_tmp_sources src_${PROJECT_NAME}_foo INTERFACE_SOURCES)
foreach(src ${_tmp_sources})
    cmake_path(GET src STEM filez)
    cmake_path(GET src FILENAME filename)
    set(MODULE_C_DEFINES __FILE_Z__=${filez} __FILE_Z_STR__=\"${filename}\")
    set_source_files_properties(${src}
        PROPERTIES COMPILE_DEFINITIONS "${MODULE_C_DEFINES}"
    )
endforeach()
  • sub1/CMakeLists.txt
roject(sub1)

include(${ROOTDIR}/foo.cmake)

add_subdirectory(module_foo)
  • sub1/module_foo/CMakeLists.txt
add_library(foo_${PROJECT_NAME})
target_link_libraries(foo_${PROJECT_NAME} src_${PROJECT_NAME}_foo)
  • sub2/CMakeLists.txt
roject(sub2)

include(${ROOTDIR}/foo.cmake)

add_subdirectory(module_foo)
  • sub2/module_foo/CMakeLists.txt
add_library(foo_${PROJECT_NAME})
target_link_libraries(foo_${PROJECT_NAME} src_${PROJECT_NAME}_foo)

sub1 and sub2 are two sub projects and build same module: foo while the source maybe different

The problem is that set_source_files_properties in foo.cmake is not working in each module_foo/CMakeLists.txt, the offical DOCS suggest use DIRECTORY then I have to call add_subdirectory(module_foo) before define the target src_${PROJECT_NAME}_foo. But when I call add_subdirectory(module_foo) means I will use src_${PROJECT_NAME}_foo and I dont want to call include(${ROOTDIR}/foo.cmake) in module_foo/CMakeLists.txt (because there are many modules, I includes them in each sub1/sub2)

That’s limit is weird, It seems broken the normal usage order.

How can I get it work while keeping the origin project stucture?