[CMake] SOURCE_GROUP command

Jesse Corrington jesse.corrington at gmail.com
Fri Nov 30 21:31:31 EST 2007


In my cmake scripts I build a single list of all my cpp and h files for the
project. At the end of the script I iterate over this list and add each file
to the correct source group based on it's path relative to the source root.
This is only for MSVC.  I am running into a problem where I end up with .h
files in the Source Files group, or .cpp files in the Header Files group. I
noticed that if I only grouped header files, or only grouped source files,
then there was no mixing, but I want both to be grouped. Below is my code
for doing this. PROJECT_SOURCE_FILES contains the complete list of source
and header files. Thanks

Jesse

# Setup source grouping for visual studio
IF( MSVC )

    FOREACH( pathSourceFile ${PROJECT_SOURCE_FILES} )

        GET_FILENAME_COMPONENT( pathSourceGroup ${pathSourceFile} PATH )

        IF( NOT ${pathSourceGroup} STREQUAL ${CMAKE_SOURCE_DIR} )

            # Make the path relative to the base source path
            STRING( REPLACE ${CMAKE_SOURCE_DIR} "" pathSourceGroup
${pathSourceGroup} )

            # Remove starting / and \
            STRING( SUBSTRING ${pathSourceGroup} 0 1 firstChar )
            IF( firstChar STREQUAL "/" OR
                firstChar STREQUAL "\\" )

                STRING( LENGTH ${pathSourceGroup} strLen )
                MATH( EXPR strLen "${strLen} - 1" )
                STRING( SUBSTRING ${pathSourceGroup} 1 ${strLen}
pathSourceGroup )
            ENDIF()

            # Replace / with \ so the source groups work correctly in MSVC
            STRING( REPLACE "/" "\\" pathSourceGroup ${pathSourceGroup} )

            # Add file to the source group
            GET_FILENAME_COMPONENT( fileExtension ${pathSourceFile} EXT )
            IF( ${fileExtension} MATCHES ".c" OR
                ${fileExtension} MATCHES ".cpp" )
                SOURCE_GROUP( "Source Files\\${pathSourceGroup}" FILES
${pathSourceFile} )
            ELSEIF( ${fileExtension} MATCHES ".h" OR
                    ${fileExtension} MATCHES ".hpp" )
                SOURCE_GROUP( "Header Files\\${pathSourceGroup}" FILES
${pathSourceFile} )
            ELSE()
                MESSAGE( SEND_ERROR "Source grouping failed on file
${pathSourceFile}" )
            ENDIF()

        ENDIF()

    ENDFOREACH()
ENDIF()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://public.kitware.com/pipermail/cmake/attachments/20071130/0038c065/attachment-0001.html


More information about the CMake mailing list