cmakebuildlibrariesbuild-dependencies

Should I add headers as INTERFACE target sources, or just set an INTERFACE target include directory?


In a repository using CMake, I have a library foo which gets compiled from foo.c. There is also a file foo.h which, for the sake of discussion, is only necessary when compiling code against foo. Both the compiled library and foo.h get installed.

Now, how should I "announce" foo.h to dependent targets? Should I write:

target_sources(foo INTERFACE "$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>/foo.h")

, or perhaps:

target_include_directories(foo INTERFACE "$<BUILD_INTERFACE:${GENERATED_INCLUDE_DIR}>")

or - maybe both?


Solution

  • Only the latter. foo.h is not one of the first-party sources of the linkee, which is what (INTERFACE_)SOURCES is supposed to model. Then the target foo in order to be used requires that the linkee can find its headers; those belong in INTERFACE_INCLUDE_DIRECTORIES (which target_include_directories sets).