Home > Back-end >  CMake add list of subdirectories
CMake add list of subdirectories

Time:07-11

In my CMake project I need to add a list of subdirectories.

  1. The correct way is not nice because I can not pass a list:
    add_subdirectory(Helpers)
    add_subdirectory(Lib1)
    add_subdirectory(Lib2)
    
  2. subdirs can pass a list, but is deprecated:
    subdirs(Helpers
            Lib1
            Lib2)
    

Is there a way to add subdirectories as a list? It seems like a common usecase.

If not: Why was it discontinued?

CodePudding user response:

You could use foreach():

foreach(SUBDIR IN ITEMS
    Helpers
    Lib1
    Lib2
)
    add_subdirectory(${SUBDIR})
endforeach()

You could even wrap this in a custom function

function(my_subdirs SUB1)
    foreach(SUBDIR IN ITEMS ${SUB1} ${ARGN})
        add_subdirectory(${SUBDIR})
    endforeach()
endfunction()

...

my_subdirs(
    Helpers
    Lib1
    Lib2
)
  • Related