How to propagate source_group from INTERFACE library?


I build a C++ project with CMake and currently use an INTERFACE add_library for including a header-only library.

It works nicely propagating headers to library it linked to via target_sources / target_include_directories commands, but at the same time source_group do not work properly, and I do not see sub-folders in Visual Studio.

The folders are turned on, and source_group works fine in other cases.

I believe I’ve encountered this situation as well with interface libraries. They don’t nicely work with source_group and here is the ugly workaround I came up with.

I basically ripped this code from our cmake but changed the names around.

    set_directory_properties(PROPERTIES VS_STARTUP_PROJECT foobar)

    get_target_property(foobar_sources foobar SOURCES)

    # TODO: This code is really awkward in my opinion
    # But much better than the default behavior.
    # X is an interface library. Here is what that means.
    # It's source files don't get added to foobar sources property.
    # Meaning that it will get the default labels in visual studio SOURCE/HEADER
    # This is undesirable since it's inconsistent with everything else.
    # Currently my only solution is to manually query for this property. To ensure a pleasant
    # IDE experience.
    # This isn't ideal since it's different from everything else and doesn't allow work with aliased targets
    if (TARGET x)
        get_target_property(x_sources x INTERFACE_SOURCES)

    # Display the folders directory structure in Visual Studio
    # If this isn't done then you just get generic Header/Source Files filters
    source_group(TREE  ${FOOBAR_SOURCE_DIR}/
                 FILES ${foobar_sources} ${x_sources }

If anyone has a better way to do this please tell me.

Hi there,

Any update on this would be cool, facing same issue here