target_sources() and target_include_directories() behaviour

i am not sure about how cmake retrieves header files. (see cmake code below)
my expectation is that it looks only what is defined in target_include_directories().

According to the cmake text file and the directory structure i would expect a compiler error since the path to “DummyTest_prv.h” is not explicitly described.
but compiling/linking goes through as it seems DummyTest_prv.h is discovered “somehow” by CMake.

Since the build system is Unix Makefile, i found under build/CMakeFiles/myapp.dir/src/DummyTest_prv.c.o.d:
CMakeFiles/myapp.dir/src/DummyTest_prv.c.o:
/home/yof1dy/private/test/rbDyDummyTest/src/DummyTest_prv.c
/usr/include/stdc-predef.h
/home/yof1dy/private/test/rbDyDummyTest/src/DummyTest_prv.h

is it intended like this? i couldn’t find any documentation.

Thanks CMake Team.

cmake code below


# folder structure

#.

#├── CMakeLists.txt

#├── inc

#│ └── DummyTest.h

#└── src

# ├── DummyTest.c

# ├── DummyTest_prv.c

# └── DummyTest_prv.h

set minimum cmake version

cmake_minimum_required(VERSION 3.5 FATAL_ERROR)

# project name and language

project(Helloworld LANGUAGES C)

add_executable(myapp)

target_include_directories(myapp

PUBLIC

${CMAKE_CURRENT_SOURCE_DIR}/inc/

)

target_sources(myapp

PRIVATE

${CMAKE_CURRENT_SOURCE_DIR}/src/DummyTest.c

${CMAKE_CURRENT_SOURCE_DIR}/src/DummyTest_prv.c

)

target_compile_options(myapp

PUBLIC

-Wall

)

It’s not discovered by CMake, but by the compiler (CMake asks the compiler for the dependencies to create those “*.d” files).

So this is a consequence of header search rules implemented by the compiler. Specifically, the compiler also searches the directory where the including file is. GCC even prefers this if you use #include "header.h" (so if you use quotes as opposed to angle brackets).

Thanks for the quick answer.
when you say:
”Specifically, the compiler also searches the directory where the including file is.”
–> do you mean the compiler searches the header files in the folder where the src file is located?

Yes.
Look at the documentation (gcc-specific): Search Path (The C Preprocessor)

1 Like