[CMake] Should header files be listed for a target?

Kyle Edwards kyle.edwards at kitware.com
Wed Sep 11 14:49:28 EDT 2019


On Wed, 2019-09-11 at 21:40 +0300, Avraham Shukron wrote:
> Hi!
> 
> I'm pretty new to cmake and I came across a question which I could
> not find any information about in the official documentation or blog
> posts.
> 
> When adding a target through add_library / add_executable - should
> the header files of the target also be listed?
> The question also applies to target_sources I guess.
> 
> On one hand - as far as I can tell it compiles perfectly fine without
> doing so, and the implicit dependency is also recognized (e.g if the
> header changes - the target will be recompiled)
> In addition most of the online examples do not list headers.
> 
> On the other hand - it seems wrong not to list them. They ARE part of
> the target, even if they do not passed to the compiler directly.
> I can also assume that some IDEs will want to know about the
> existence of these headers and their relationship with the target.
> 
> So what is the correct answer? should header files be listed as part
> of the target?

You can list them or not list them. CMake will recognize them as header
files and ignore them (not attempt to compile them.) It's a matter of
personal preference. CMake's own CMake script lists them, but there are
plenty of projects that don't and work just fine.

> Another question - how does cmake know to create the
> dependency between the target and the header file, even when it is
> not listed explicitly?

It uses GCC's -MD and -MF options (and the equivalents for other
compilers), which spits out the header dependency information.

Kyle


More information about the CMake mailing list