Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between include_directories and target_include_directories in CMake?

Tags:

c++

cmake

People also ask

What does Include_directories do in CMake?

Add include directories to the build. Add the given directories to those the compiler uses to search for include files. Relative paths are interpreted as relative to the current source directory.

What does target include directories do?

Specifies include directories to use when compiling a given target. The named <target> must have been created by a command such as add_executable() or add_library() and must not be an ALIAS target. By using AFTER or BEFORE explicitly, you can select between appending and prepending, independent of the default.

What are targets in CMake?

Introduction. A CMake-based buildsystem is organized as a set of high-level logical targets. Each target corresponds to an executable or library, or is a custom target containing custom commands.

How do you add a path to CMake?

To include headers in CMake targets, use the command target_include_directories(...) . Depending on the purpose of the included directories, you will need to define the scope specifier – either PUBLIC , PRIVATE or INTERFACE .


include_directories(x/y) affects directory scope. All targets in this CMakeList, as well as those in all subdirectories added after the point of its call, will have the path x/y added to their include path.

target_include_directories(t x/y) has target scope—it adds x/y to the include path for target t.

You want the former one if all of your targets use the include directories in question. You want the latter one if the path is specific to a target, or if you want finer control of the path's visibility. The latter comes from the fact that target_include_directories() supports the PRIVATE, PUBLIC, and INTERFACE qualifiers.


Beside what Angew's answer correctly says, another very important difference between include_directories and target_include_directories is that, when used with PUBLIC or INTERFACE, the latter populate the INTERFACE_INCLUDE_DIRECTORIES property of the target. This property is useful when another target uses target_link_libraries to link to the original target, as the linking target will have automatically those include directories added. See example.

This important feature is pretty well hidden in the documentation: target_include_directories mention populating INTERFACE_INCLUDE_DIRECTORIES, whose documentation says:

When target dependencies are specified using target_link_libraries(), CMake will read this property from all target dependencies to determine the build properties of the consumer.


As @Angew said, the very difference is :

1, include_directories() is accessible for all the files in the source-tree 2, target_include_directories() is-only accessible for a specific target when compile.