Benefits of using target_sources() on INTERFACE targets?

Should I, and why should I add my headers to header only libraries?

add_library(headeronly INTERFACE)
target_include_directories(headeronly "include")
target_sources(headeronly INTERFACE "include/header.h")

The headers will appear in the source list of all using libraries. They are not compiled anyways unless used. What are the benefits of this?

I can only think of one thing, which is, they are included in the source view for some generators (e.g. Visual Studio). (Not tested!) However, I am not sure if you would even want this. They may appear more than once!

I’d personally add the headers to the add_library list. Adding them to target_sources adds them to all consumers of your library, which isn’t usually what you actually mean. Getting them to show up in the IDE generators is another benefit (though I don’t remember if INTERFACE targets show up there in the first place).

I tried it:

add_library(interface_lib INTERFACE)
target_sources(interface_lib INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/interface_lib.cpp)

add_library(header_only INTERFACE)
target_sources(interface_lib INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/header_only.h)

add_library(static_lib static_lib.cpp)
target_link_libraries(static_lib interface_lib header_only)

add_executable(main main.cpp)
target_link_libraries(main static_lib)

Results in:
2020-02-18 14_21_45-target_sources - Microsoft Visual Studio

So header files are added to the header section and sources are added to the source section (i am not sure when or where they are compiled, because this looks to me like ther should be duplicate symbols of interface_lib.cpp in main, but there are not)

I am still asking if its good practice to add the header to a header only library and why?

Well, since INTERFACE libraries aren’t showing up in the IDE, I guess that’s your decision then (assuming you don’t get duplicate symbols on that cpp file). I expect that once https://gitlab.kitware.com/cmake/cmake/issues/19145 gets fixed, the situation would look a little different.