[CMake] [Cmake] Detect caller project for a sub-project

Michael Hertling mhertling at online.de
Thu Jun 10 17:38:08 EDT 2010


On 06/10/2010 12:18 PM, Filippo Trimoldi wrote:
> If I have a CMake project organized in more than two level, i.e.
> 
> CMakeLists.txt:
> PROJECT(A)
> add_subdirectories(./projectB)
> 
> ./projectB/CMakeLists.txt:
> PROJECT(B)
> add_subdirectories(${PROJECT_SOURCE_DIR}/projectC)
> 
> ./projectB/projectC/CMakeLists.txt:
> PROJECT(C)
> 
> is there some kind of way for a project to detect the name of the project
> from which it was added? In this example, can C know that was added by B?
> (and B was added by A?)

Possibly, a function like the following can be used:

FUNCTION(GET_PARENT_PROJECT RESULT)
    SET(PARENT_SOURCE_DIRS)
    GET_DIRECTORY_PROPERTY(v VARIABLES)
    FOREACH(i IN LISTS v)
        IF(i MATCHES "_SOURCE_DIR\$"
           AND NOT i MATCHES "^(CMAKE|PROJECT|${PROJECT_NAME})_")
            LIST(APPEND PARENT_SOURCE_DIRS ${i})
        ENDIF()
    ENDFOREACH()
    LIST(LENGTH PARENT_SOURCE_DIRS n)
    IF(n GREATER 0)
        LIST(REVERSE PARENT_SOURCE_DIRS)
        LIST(GET PARENT_SOURCE_DIRS 0 p)
    ELSE()
        SET(p "")
    ENDIF()
    STRING(REGEX REPLACE "^(.*)_SOURCE_DIR\$" "\\1" p ${p})
    SET(${RESULT} ${p} PARENT_SCOPE)
ENDFUNCTION()

It scans the current directory's VARIABLES property for source
directories and extracts the parent project's name from the nearest
source directory which isn't the current project's one. Of course, this
relies on the absence of any foreign SOURCE_DIR variables as well as on
the assumption that the SOURCE_DIRs occur in descending order within the
VARIABLES directory property. While that's obvious it is not assured by
the documentation, so this approach isn't really bulletproof.

In general, I would join AM's advice: You may refer from the "outer"
project to the "inner" project, but you should not do vice versa.

Regards,

Michael


More information about the CMake mailing list