CMake : How to get the name of all subdirectories of a directory?

  1. Use this macro:

    MACRO(SUBDIRLIST result curdir)
      FILE(GLOB children RELATIVE ${curdir} ${curdir}/*)
      SET(dirlist "")
      FOREACH(child ${children})
        IF(IS_DIRECTORY ${curdir}/${child})
          LIST(APPEND dirlist ${child})
        ENDIF()
      ENDFOREACH()
      SET(${result} ${dirlist})
    ENDMACRO()
    

    Example:

    SUBDIRLIST(SUBDIRS ${MY_CURRENT_DIR})
    
  2. Use foreach:

    FOREACH(subdir ${SUBDIRS})
      ADD_SUBDIRECTORY(${subdir})
    ENDFOREACH()
    


In regard to answer above: Use this macro:

MACRO(SUBDIRLIST result curdir)
  FILE(GLOB children RELATIVE ${curdir} ${curdir}/*)
  SET(dirlist "")
  FOREACH(child ${children})
    IF(IS_DIRECTORY ${curdir}/${child})
      LIST(APPEND dirlist ${child})
    ENDIF()
  ENDFOREACH()
  SET(${result} ${dirlist})
ENDMACRO()

Example:

SUBDIRLIST(SUBDIRS ${MY_CURRENT_DIR})

I had trouble with this FILE(GLOB command. (I'm on cmake 3.17.3) Otherwise the macro works great. I was getting FILE GLOB errors, something like "FILE GLOB requires a glob expression after the directory." (Maybe it didn't like RELATIVE and/or just using the curdir as the fourth paramter.)

I had to use:

FILE(GLOB children ${curdir}/*)

(taking out RELATIVE and the first ${curdir} (Please note my cmake version above, that could've been my issue (I'm unfamiliar with glob so far.).)

Tags:

Cmake