index.rst 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. Importing and Exporting Targets
  2. *******************************
  3. .. only:: html
  4. .. contents::
  5. In this guide, we will present the concept of :prop_tgt:`IMPORTED` targets
  6. and demonstrate how to import existing executable or library files from disk
  7. into a CMake project. We will then show how CMake supports exporting targets
  8. from one CMake-based project and importing them into another. Finally, we
  9. will demonstrate how to package a project with a configuration file to allow
  10. for easy integration into other CMake projects. This guide and the complete
  11. example source code can be found in the ``Help/guide/importing-exporting``
  12. directory of the CMake source code tree.
  13. Importing Targets
  14. =================
  15. :prop_tgt:`IMPORTED` targets are used to convert files outside of a CMake
  16. project into logical targets inside of the project. :prop_tgt:`IMPORTED`
  17. targets are created using the ``IMPORTED`` option of the
  18. :command:`add_executable` and :command:`add_library` commands. No build
  19. files are generated for :prop_tgt:`IMPORTED` targets. Once imported,
  20. :prop_tgt:`IMPORTED` targets may be referenced like any other target within
  21. the project and provide a convenient, flexible reference to outside
  22. executables and libraries.
  23. By default, the :prop_tgt:`IMPORTED` target name has scope in the directory in
  24. which it is created and below. We can use the ``GLOBAL`` option to extended
  25. visibility so that the target is accessible globally in the build system.
  26. Details about the :prop_tgt:`IMPORTED` target are specified by setting
  27. properties whose names begin in ``IMPORTED_`` and ``INTERFACE_``. For example,
  28. :prop_tgt:`IMPORTED_LOCATION` contains the full path to the target on
  29. disk.
  30. Importing Executables
  31. ---------------------
  32. To start, we will walk through a simple example that creates an
  33. :prop_tgt:`IMPORTED` executable target and then references it from the
  34. :command:`add_custom_command` command.
  35. We'll need to do some setup to get started. We want to create an executable
  36. that when run creates a basic ``main.cc`` file in the current directory. The
  37. details of this project are not important. Navigate to
  38. ``Help/guide/importing-exporting/MyExe``, create a build directory, run
  39. :manual:`cmake <cmake(1)>` and build and install the project.
  40. .. code-block:: console
  41. $ cd Help/guide/importing-exporting/MyExe
  42. $ mkdir build
  43. $ cd build
  44. $ cmake ..
  45. $ cmake --build .
  46. $ cmake --install . --prefix <install location>
  47. $ <install location>/myexe
  48. $ ls
  49. [...] main.cc [...]
  50. Now we can import this executable into another CMake project. The source code
  51. for this section is available in ``Help/guide/importing-exporting/Importing``.
  52. In the CMakeLists file, use the :command:`add_executable` command to create a
  53. new target called ``myexe``. Use the ``IMPORTED`` option to tell CMake that
  54. this target references an executable file located outside of the project. No
  55. rules will be generated to build it and the :prop_tgt:`IMPORTED` target
  56. property will be set to ``true``.
  57. .. literalinclude:: Importing/CMakeLists.txt
  58. :language: cmake
  59. :start-after: # Add executable
  60. :end-before: # Set imported location
  61. Next, set the :prop_tgt:`IMPORTED_LOCATION` property of the target using
  62. the :command:`set_property` command. This will tell CMake the location of the
  63. target on disk. The location may need to be adjusted to the
  64. ``<install location>`` specified in the previous step.
  65. .. literalinclude:: Importing/CMakeLists.txt
  66. :language: cmake
  67. :start-after: # Set imported location
  68. :end-before: # Add custom command
  69. We can now reference this :prop_tgt:`IMPORTED` target just like any target
  70. built within the project. In this instance, let's imagine that we want to use
  71. the generated source file in our project. Use the :prop_tgt:`IMPORTED`
  72. target in the :command:`add_custom_command` command:
  73. .. literalinclude:: Importing/CMakeLists.txt
  74. :language: cmake
  75. :start-after: # Add custom command
  76. :end-before: # Use source file
  77. As ``COMMAND`` specifies an executable target name, it will automatically be
  78. replaced by the location of the executable given by the
  79. :prop_tgt:`IMPORTED_LOCATION` property above.
  80. Finally, use the output from :command:`add_custom_command`:
  81. .. literalinclude:: Importing/CMakeLists.txt
  82. :language: cmake
  83. :start-after: # Use source file
  84. Importing Libraries
  85. -------------------
  86. In a similar manner, libraries from other projects may be accessed through
  87. :prop_tgt:`IMPORTED` targets.
  88. Note: The full source code for the examples in this section is not provided
  89. and is left as an exercise for the reader.
  90. In the CMakeLists file, add an :prop_tgt:`IMPORTED` library and specify its
  91. location on disk:
  92. .. code-block:: cmake
  93. add_library(foo STATIC IMPORTED)
  94. set_property(TARGET foo PROPERTY
  95. IMPORTED_LOCATION "/path/to/libfoo.a")
  96. Then use the :prop_tgt:`IMPORTED` library inside of our project:
  97. .. code-block:: cmake
  98. add_executable(myexe src1.c src2.c)
  99. target_link_libraries(myexe PRIVATE foo)
  100. On Windows, a .dll and its .lib import library may be imported together:
  101. .. code-block:: cmake
  102. add_library(bar SHARED IMPORTED)
  103. set_property(TARGET bar PROPERTY
  104. IMPORTED_LOCATION "c:/path/to/bar.dll")
  105. set_property(TARGET bar PROPERTY
  106. IMPORTED_IMPLIB "c:/path/to/bar.lib")
  107. add_executable(myexe src1.c src2.c)
  108. target_link_libraries(myexe PRIVATE bar)
  109. A library with multiple configurations may be imported with a single target:
  110. .. code-block:: cmake
  111. find_library(math_REL NAMES m)
  112. find_library(math_DBG NAMES md)
  113. add_library(math STATIC IMPORTED GLOBAL)
  114. set_target_properties(math PROPERTIES
  115. IMPORTED_LOCATION "${math_REL}"
  116. IMPORTED_LOCATION_DEBUG "${math_DBG}"
  117. IMPORTED_CONFIGURATIONS "RELEASE;DEBUG"
  118. )
  119. add_executable(myexe src1.c src2.c)
  120. target_link_libraries(myexe PRIVATE math)
  121. The generated build system will link ``myexe`` to ``m.lib`` when built in the
  122. release configuration, and ``md.lib`` when built in the debug configuration.
  123. Exporting Targets
  124. =================
  125. While :prop_tgt:`IMPORTED` targets on their own are useful, they still
  126. require that the project that imports them knows the locations of the target
  127. files on disk. The real power of :prop_tgt:`IMPORTED` targets is when the
  128. project providing the target files also provides a CMake file to help import
  129. them. A project can be setup to produce the necessary information so that it
  130. can easily be used by other CMake projects be it from a build directory, a
  131. local install or when packaged.
  132. In the remaining sections, we will walk through a set of example projects
  133. step-by-step. The first project will create and install a library and
  134. corresponding CMake configuration and package files. The second project will
  135. use the generated package.
  136. Let's start by looking at the ``MathFunctions`` project in the
  137. ``Help/guide/importing-exporting/MathFunctions`` directory. Here we have a
  138. header file ``MathFunctions.h`` that declares a ``sqrt`` function:
  139. .. literalinclude:: MathFunctions/MathFunctions.h
  140. :language: c++
  141. And a corresponding source file ``MathFunctions.cxx``:
  142. .. literalinclude:: MathFunctions/MathFunctions.cxx
  143. :language: c++
  144. Don't worry too much about the specifics of the C++ files, they are just meant
  145. to be a simple example that will compile and run on many build systems.
  146. Now we can create a ``CMakeLists.txt`` file for the ``MathFunctions``
  147. project. Start by specifying the :command:`cmake_minimum_required` version and
  148. :command:`project` name:
  149. .. literalinclude:: MathFunctions/CMakeLists.txt
  150. :language: cmake
  151. :end-before: # create library
  152. Create a library called ``MathFunctions`` with the :command:`add_library`
  153. command:
  154. .. literalinclude:: MathFunctions/CMakeLists.txt
  155. :language: cmake
  156. :start-after: # create library
  157. :end-before: # add include directories
  158. And then use the :command:`target_include_directories` command to specify the
  159. include directories for the target:
  160. .. literalinclude:: MathFunctions/CMakeLists.txt
  161. :language: cmake
  162. :start-after: # add include directories
  163. :end-before: # install the target and create export-set
  164. We need to tell CMake that we want to use different include directories
  165. depending on if we're building the library or using it from an installed
  166. location. If we don't do this, when CMake creates the export information it
  167. will export a path that is specific to the current build directory
  168. and will not be valid for other projects. We can use
  169. :manual:`generator expressions <cmake-generator-expressions(7)>` to specify
  170. that if we're building the library include the current source directory.
  171. Otherwise, when installed, include the ``include`` directory. See the `Creating
  172. Relocatable Packages`_ section for more details.
  173. The :command:`install(TARGETS)` and :command:`install(EXPORT)` commands
  174. work together to install both targets (a library in our case) and a CMake
  175. file designed to make it easy to import the targets into another CMake project.
  176. First, in the :command:`install(TARGETS)` command we will specify the target,
  177. the ``EXPORT`` name and the destinations that tell CMake where to install the
  178. targets.
  179. .. literalinclude:: MathFunctions/CMakeLists.txt
  180. :language: cmake
  181. :start-after: # install the target and create export-set
  182. :end-before: # install header file
  183. Here, the ``EXPORT`` option tells CMake to create an export called
  184. ``MathFunctionsTargets``. The generated :prop_tgt:`IMPORTED` targets have
  185. appropriate properties set to define their
  186. :ref:`usage requirements <Target Usage Requirements>`, such as
  187. :prop_tgt:`INTERFACE_INCLUDE_DIRECTORIES`,
  188. :prop_tgt:`INTERFACE_COMPILE_DEFINITIONS` and other relevant built-in
  189. ``INTERFACE_`` properties. The ``INTERFACE`` variant of user-defined
  190. properties listed in :prop_tgt:`COMPATIBLE_INTERFACE_STRING` and other
  191. :ref:`Compatible Interface Properties` are also propagated to the
  192. generated :prop_tgt:`IMPORTED` targets. For example, in this case, the
  193. :prop_tgt:`IMPORTED` target will have its
  194. :prop_tgt:`INTERFACE_INCLUDE_DIRECTORIES` property populated with
  195. the directory specified by the ``INCLUDES DESTINATION`` property. As a
  196. relative path was given, it is treated as relative to the
  197. :variable:`CMAKE_INSTALL_PREFIX`.
  198. Note, we have *not* asked CMake to install the export yet.
  199. We don't want to forget to install the ``MathFunctions.h`` header file with the
  200. :command:`install(FILES)` command. The header file should be installed to the
  201. ``include`` directory, as specified by the
  202. :command:`target_include_directories` command above.
  203. .. literalinclude:: MathFunctions/CMakeLists.txt
  204. :language: cmake
  205. :start-after: # install header file
  206. :end-before: # generate and install export file
  207. Now that the ``MathFunctions`` library and header file are installed, we also
  208. need to explicitly install the ``MathFunctionsTargets`` export details. Use
  209. the :command:`install(EXPORT)` command to export the targets in
  210. ``MathFunctionsTargets``, as defined by the :command:`install(TARGETS)`
  211. command.
  212. .. literalinclude:: MathFunctions/CMakeLists.txt
  213. :language: cmake
  214. :start-after: # generate and install export file
  215. :end-before: # include CMakePackageConfigHelpers macro
  216. This command generates the ``MathFunctionsTargets.cmake`` file and arranges
  217. to install it to ``lib/cmake``. The file contains code suitable for
  218. use by downstreams to import all targets listed in the install command from
  219. the installation tree.
  220. The ``NAMESPACE`` option will prepend ``MathFunctions::`` to the target names
  221. as they are written to the export file. This convention of double-colons
  222. gives CMake a hint that the name is an :prop_tgt:`IMPORTED` target when it
  223. is used by downstream projects. This way, CMake can issue a diagnostic
  224. message if the package providing it was not found.
  225. The generated export file contains code that creates an :prop_tgt:`IMPORTED` library.
  226. .. code-block:: cmake
  227. # Create imported target MathFunctions::MathFunctions
  228. add_library(MathFunctions::MathFunctions STATIC IMPORTED)
  229. set_target_properties(MathFunctions::MathFunctions PROPERTIES
  230. INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
  231. )
  232. This code is very similar to the example we created by hand in the
  233. `Importing Libraries`_ section. Note that ``${_IMPORT_PREFIX}`` is computed
  234. relative to the file location.
  235. An outside project may load this file with the :command:`include` command and
  236. reference the ``MathFunctions`` library from the installation tree as if it
  237. were built in its own tree. For example:
  238. .. code-block:: cmake
  239. :linenos:
  240. include(${INSTALL_PREFIX}/lib/cmake/MathFunctionTargets.cmake)
  241. add_executable(myexe src1.c src2.c )
  242. target_link_libraries(myexe PRIVATE MathFunctions::MathFunctions)
  243. Line 1 loads the target CMake file. Although we only exported a single
  244. target, this file may import any number of targets. Their locations are
  245. computed relative to the file location so that the install tree may be
  246. easily moved. Line 3 references the imported ``MathFunctions`` library. The
  247. resulting build system will link to the library from its installed location.
  248. Executables may also be exported and imported using the same process.
  249. Any number of target installations may be associated with the same
  250. export name. Export names are considered global so any directory may
  251. contribute a target installation. The :command:`install(EXPORT)` command only
  252. needs to be called once to install a file that references all targets. Below
  253. is an example of how multiple exports may be combined into a single
  254. export file, even if they are in different subdirectories of the project.
  255. .. code-block:: cmake
  256. # A/CMakeLists.txt
  257. add_executable(myexe src1.c)
  258. install(TARGETS myexe DESTINATION lib/myproj
  259. EXPORT myproj-targets)
  260. # B/CMakeLists.txt
  261. add_library(foo STATIC foo1.c)
  262. install(TARGETS foo DESTINATION lib EXPORTS myproj-targets)
  263. # Top CMakeLists.txt
  264. add_subdirectory (A)
  265. add_subdirectory (B)
  266. install(EXPORT myproj-targets DESTINATION lib/myproj)
  267. Creating Packages
  268. -----------------
  269. At this point, the ``MathFunctions`` project is exporting the target
  270. information required to be used by other projects. We can make this project
  271. even easier for other projects to use by generating a configuration file so
  272. that the CMake :command:`find_package` command can find our project.
  273. To start, we will need to make a few additions to the ``CMakeLists.txt``
  274. file. First, include the :module:`CMakePackageConfigHelpers` module to get
  275. access to some helper functions for creating config files.
  276. .. literalinclude:: MathFunctions/CMakeLists.txt
  277. :language: cmake
  278. :start-after: # include CMakePackageConfigHelpers macro
  279. :end-before: # set version
  280. Then we will create a package configuration file and a package version file.
  281. Creating a Package Configuration File
  282. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  283. Use the :command:`configure_package_config_file` command provided by the
  284. :module:`CMakePackageConfigHelpers` to generate the package configuration
  285. file. Note that this command should be used instead of the plain
  286. :command:`configure_file` command. It helps to ensure that the resulting
  287. package is relocatable by avoiding hardcoded paths in the installed
  288. configuration file. The path given to ``INSTALL_DESTINATION`` must be the
  289. destination where the ``MathFunctionsConfig.cmake`` file will be installed.
  290. We will examine the contents of the package configuration file in the next
  291. section.
  292. .. literalinclude:: MathFunctions/CMakeLists.txt
  293. :language: cmake
  294. :start-after: # create config file
  295. :end-before: # install config files
  296. Install the generated configuration files with the :command:`INSTALL(files)`
  297. command. Both ``MathFunctionsConfigVersion.cmake`` and
  298. ``MathFunctionsConfig.cmake`` are installed to the same location, completing
  299. the package.
  300. .. literalinclude:: MathFunctions/CMakeLists.txt
  301. :language: cmake
  302. :start-after: # install config files
  303. :end-before: # generate the export targets for the build tree
  304. Now we need to create the package configuration file itself. In this case, the
  305. ``Config.cmake.in`` file is very simple but sufficient to allow downstreams
  306. to use the :prop_tgt:`IMPORTED` targets.
  307. .. literalinclude:: MathFunctions/Config.cmake.in
  308. The first line of the file contains only the string ``@PACKAGE_INIT@``. This
  309. expands when the file is configured and allows the use of relocatable paths
  310. prefixed with ``PACKAGE_``. It also provides the ``set_and_check()`` and
  311. ``check_required_components()`` macros.
  312. The ``check_required_components`` helper macro ensures that all requested,
  313. non-optional components have been found by checking the
  314. ``<Package>_<Component>_FOUND`` variables for all required components. This
  315. macro should be called at the end of the package configuration file even if the
  316. package does not have any components. This way, CMake can make sure that the
  317. downstream project hasn't specified any non-existent components. If
  318. ``check_required_components`` fails, the ``<Package>_FOUND`` variable is set to
  319. FALSE, and the package is considered to be not found.
  320. The ``set_and_check()`` macro should be used in configuration files instead
  321. of the normal ``set()`` command for setting directories and file locations.
  322. If a referenced file or directory does not exist, the macro will fail.
  323. If any macros should be provided by the ``MathFunctions`` package, they should
  324. be in a separate file which is installed to the same location as the
  325. ``MathFunctionsConfig.cmake`` file, and included from there.
  326. **All required dependencies of a package must also be found in the package
  327. configuration file.** Let's imagine that we require the ``Stats`` library in
  328. our project. In the CMakeLists file, we would add:
  329. .. code-block:: cmake
  330. find_package(Stats 2.6.4 REQUIRED)
  331. target_link_libraries(MathFunctions PUBLIC Stats::Types)
  332. As the ``Stats::Types`` target is a ``PUBLIC`` dependency of ``MathFunctions``,
  333. downstreams must also find the ``Stats`` package and link to the
  334. ``Stats::Types`` library. The ``Stats`` package should be found in the
  335. configuration file to ensure this.
  336. .. code-block:: cmake
  337. include(CMakeFindDependencyMacro)
  338. find_dependency(Stats 2.6.4)
  339. The ``find_dependency`` macro from the :module:`CMakeFindDependencyMacro`
  340. module helps by propagating whether the package is ``REQUIRED``, or
  341. ``QUIET``, etc. The ``find_dependency`` macro also sets
  342. ``MathFunctions_FOUND`` to ``False`` if the dependency is not found, along
  343. with a diagnostic that the ``MathFunctions`` package cannot be used without
  344. the ``Stats`` package.
  345. **Exercise:** Add a required library to the ``MathFunctions`` project.
  346. Creating a Package Version File
  347. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  348. The :module:`CMakePackageConfigHelpers` module provides the
  349. :command:`write_basic_package_version_file` command for creating a simple
  350. package version file. This file is read by CMake when :command:`find_package`
  351. is called to determine the compatibility with the requested version, and to set
  352. some version-specific variables such as ``<PackageName>_VERSION``,
  353. ``<PackageName>_VERSION_MAJOR``, ``<PackageName>_VERSION_MINOR``, etc. See
  354. :manual:`cmake-packages <cmake-packages(7)>` documentation for more details.
  355. .. literalinclude:: MathFunctions/CMakeLists.txt
  356. :language: cmake
  357. :start-after: # set version
  358. :end-before: # create config file
  359. In our example, ``MathFunctions_MAJOR_VERSION`` is defined as a
  360. :prop_tgt:`COMPATIBLE_INTERFACE_STRING` which means that it must be
  361. compatible among the dependencies of any depender. By setting this
  362. custom defined user property in this version and in the next version of
  363. ``MathFunctions``, :manual:`cmake <cmake(1)>` will issue a diagnostic if
  364. there is an attempt to use version 3 together with version 4. Packages can
  365. choose to employ such a pattern if different major versions of the package
  366. are designed to be incompatible.
  367. Exporting Targets from the Build Tree
  368. -------------------------------------
  369. Typically, projects are built and installed before being used by an outside
  370. project. However, in some cases, it is desirable to export targets directly
  371. from a build tree. The targets may then be used by an outside project that
  372. references the build tree with no installation involved. The :command:`export`
  373. command is used to generate a file exporting targets from a project build tree.
  374. If we want our example project to also be used from a build directory we only
  375. have to add the following to ``CMakeLists.txt``:
  376. .. literalinclude:: MathFunctions/CMakeLists.txt
  377. :language: cmake
  378. :start-after: # generate the export targets for the build tree
  379. Here we use the :command:`export` command to generate the export targets for
  380. the build tree. In this case, we'll create a file called
  381. ``MathFunctionsTargets.cmake`` in the ``cmake`` subdirectory of the build
  382. directory. The generated file contains the required code to import the target
  383. and may be loaded by an outside project that is aware of the project build
  384. tree. This file is specific to the build-tree, and **is not relocatable**.
  385. It is possible to create a suitable package configuration file and package
  386. version file to define a package for the build tree which may be used without
  387. installation. Consumers of the build tree can simply ensure that the
  388. :variable:`CMAKE_PREFIX_PATH` contains the build directory, or set the
  389. ``MathFunctions_DIR`` to ``<build_dir>/MathFunctions`` in the cache.
  390. An example application of this feature is for building an executable on a host
  391. platform when cross-compiling. The project containing the executable may be
  392. built on the host platform and then the project that is being cross-compiled
  393. for another platform may load it.
  394. Building and Installing a Package
  395. ---------------------------------
  396. At this point, we have generated a relocatable CMake configuration for our
  397. project that can be used after the project has been installed. Let's try to
  398. build the ``MathFunctions`` project:
  399. .. code-block:: console
  400. mkdir MathFunctions_build
  401. cd MathFunctions_build
  402. cmake ../MathFunctions
  403. cmake --build .
  404. In the build directory, notice that the file ``MathFunctionsTargets.cmake``
  405. has been created in the ``cmake`` subdirectory.
  406. Now install the project:
  407. .. code-block:: console
  408. $ cmake --install . --prefix "/home/myuser/installdir"
  409. Creating Relocatable Packages
  410. =============================
  411. Packages created by :command:`install(EXPORT)` are designed to be relocatable,
  412. using paths relative to the location of the package itself. They must not
  413. reference absolute paths of files on the machine where the package is built
  414. that will not exist on the machines where the package may be installed.
  415. When defining the interface of a target for ``EXPORT``, keep in mind that the
  416. include directories should be specified as relative paths to the
  417. :variable:`CMAKE_INSTALL_PREFIX` but should not explicitly include the
  418. :variable:`CMAKE_INSTALL_PREFIX`:
  419. .. code-block:: cmake
  420. target_include_directories(tgt INTERFACE
  421. # Wrong, not relocatable:
  422. $<INSTALL_INTERFACE:${CMAKE_INSTALL_PREFIX}/include/TgtName>
  423. )
  424. target_include_directories(tgt INTERFACE
  425. # Ok, relocatable:
  426. $<INSTALL_INTERFACE:include/TgtName>
  427. )
  428. The ``$<INSTALL_PREFIX>``
  429. :manual:`generator expression <cmake-generator-expressions(7)>` may be used as
  430. a placeholder for the install prefix without resulting in a non-relocatable
  431. package. This is necessary if complex generator expressions are used:
  432. .. code-block:: cmake
  433. target_include_directories(tgt INTERFACE
  434. # Ok, relocatable:
  435. $<INSTALL_INTERFACE:$<INSTALL_PREFIX>/include/TgtName>
  436. )
  437. This also applies to paths referencing external dependencies.
  438. It is not advisable to populate any properties which may contain
  439. paths, such as :prop_tgt:`INTERFACE_INCLUDE_DIRECTORIES` or
  440. :prop_tgt:`INTERFACE_LINK_LIBRARIES`, with paths relevant to dependencies.
  441. For example, this code may not work well for a relocatable package:
  442. .. code-block:: cmake
  443. target_link_libraries(MathFunctions INTERFACE
  444. ${Foo_LIBRARIES} ${Bar_LIBRARIES}
  445. )
  446. target_include_directories(MathFunctions INTERFACE
  447. "$<INSTALL_INTERFACE:${Foo_INCLUDE_DIRS};${Bar_INCLUDE_DIRS}>"
  448. )
  449. The referenced variables may contain the absolute paths to libraries
  450. and include directories **as found on the machine the package was made on**.
  451. This would create a package with hard-coded paths to dependencies not
  452. suitable for relocation.
  453. Ideally such dependencies should be used through their own
  454. :ref:`IMPORTED targets <Imported Targets>` that have their own
  455. :prop_tgt:`IMPORTED_LOCATION` and usage requirement properties
  456. such as :prop_tgt:`INTERFACE_INCLUDE_DIRECTORIES` populated
  457. appropriately. Those imported targets may then be used with
  458. the :command:`target_link_libraries` command for ``MathFunctions``:
  459. .. code-block:: cmake
  460. target_link_libraries(MathFunctions INTERFACE Foo::Foo Bar::Bar)
  461. With this approach the package references its external dependencies
  462. only through the names of :ref:`IMPORTED targets <Imported Targets>`.
  463. When a consumer uses the installed package, the consumer will run the
  464. appropriate :command:`find_package` commands (via the ``find_dependency``
  465. macro described above) to find the dependencies and populate the
  466. imported targets with appropriate paths on their own machine.
  467. Using the Package Configuration File
  468. ====================================
  469. Now we're ready to create a project to use the installed ``MathFunctions``
  470. library. In this section we will be using source code from
  471. ``Help\guide\importing-exporting\Downstream``. In this directory, there is a
  472. source file called ``main.cc`` that uses the ``MathFunctions`` library to
  473. calculate the square root of a given number and then prints the results:
  474. .. literalinclude:: Downstream/main.cc
  475. :language: c++
  476. As before, we'll start with the :command:`cmake_minimum_required` and
  477. :command:`project` commands in the ``CMakeLists.txt`` file. For this project,
  478. we'll also specify the C++ standard.
  479. .. literalinclude:: Downstream/CMakeLists.txt
  480. :language: cmake
  481. :end-before: # find MathFunctions
  482. We can use the :command:`find_package` command:
  483. .. literalinclude:: Downstream/CMakeLists.txt
  484. :language: cmake
  485. :start-after: # find MathFunctions
  486. :end-before: # create executable
  487. Create an exectuable:
  488. .. literalinclude:: Downstream/CMakeLists.txt
  489. :language: cmake
  490. :start-after: # create executable
  491. :end-before: # use MathFunctions library
  492. And link to the ``MathFunctions`` library:
  493. .. literalinclude:: Downstream/CMakeLists.txt
  494. :language: cmake
  495. :start-after: # use MathFunctions library
  496. That's it! Now let's try to build the ``Downstream`` project.
  497. .. code-block:: console
  498. mkdir Downstream_build
  499. cd Downstream_build
  500. cmake ../Downstream
  501. cmake --build .
  502. A warning may have appeared during CMake configuration:
  503. .. code-block:: console
  504. CMake Warning at CMakeLists.txt:4 (find_package):
  505. By not providing "FindMathFunctions.cmake" in CMAKE_MODULE_PATH this
  506. project has asked CMake to find a package configuration file provided by
  507. "MathFunctions", but CMake did not find one.
  508. Could not find a package configuration file provided by "MathFunctions"
  509. with any of the following names:
  510. MathFunctionsConfig.cmake
  511. mathfunctions-config.cmake
  512. Add the installation prefix of "MathFunctions" to CMAKE_PREFIX_PATH or set
  513. "MathFunctions_DIR" to a directory containing one of the above files. If
  514. "MathFunctions" provides a separate development package or SDK, be sure it
  515. has been installed.
  516. Set the ``CMAKE_PREFIX_PATH`` to where MathFunctions was installed previously
  517. and try again. Ensure that the newly created executable runs as expected.
  518. Adding Components
  519. =================
  520. Let's edit the ``MathFunctions`` project to use components. The source code for
  521. this section can be found in
  522. ``Help\guide\importing-exporting\MathFunctionsComponents``. The CMakeLists file
  523. for this project adds two subdirectories: ``Addition`` and ``SquareRoot``.
  524. .. literalinclude:: MathFunctionsComponents/CMakeLists.txt
  525. :language: cmake
  526. :end-before: # include CMakePackageConfigHelpers macro
  527. Generate and install the package configuration and package version files:
  528. .. literalinclude:: MathFunctionsComponents/CMakeLists.txt
  529. :language: cmake
  530. :start-after: # include CMakePackageConfigHelpers macro
  531. If ``COMPONENTS`` are specified when the downstream uses
  532. :command:`find_package`, they are listed in the
  533. ``<PackageName>_FIND_COMPONENTS`` variable. We can use this variable to verify
  534. that all necessary component targets are included in ``Config.cmake.in``. At
  535. the same time, this function will act as a custom ``check_required_components``
  536. macro to ensure that the downstream only attempts to use supported components.
  537. .. literalinclude:: MathFunctionsComponents/Config.cmake.in
  538. Here, the ``MathFunctions_NOT_FOUND_MESSAGE`` is set to a diagnosis that the
  539. package could not be found because an invalid component was specified. This
  540. message variable can be set for any case where the ``_FOUND`` variable is set
  541. to ``False``, and will be displayed to the user.
  542. The ``Addition`` and ``SquareRoot`` directories are similar. Let's look at one
  543. of the CMakeLists files:
  544. .. literalinclude:: MathFunctionsComponents/SquareRoot/CMakeLists.txt
  545. :language: cmake
  546. Now we can build the project as described in earlier sections. To test using
  547. this package, we can use the project in
  548. ``Help\guide\importing-exporting\DownstreamComponents``. There's two
  549. differences from the previous ``Downstream`` project. First, we need to find
  550. the package components. Change the ``find_package`` line from:
  551. .. literalinclude:: Downstream/CMakeLists.txt
  552. :language: cmake
  553. :start-after: # find MathFunctions
  554. :end-before: # create executable
  555. To:
  556. .. literalinclude:: DownstreamComponents/CMakeLists.txt
  557. :language: cmake
  558. :start-after: # find MathFunctions
  559. :end-before: # create executable
  560. and the ``target_link_libraries`` line from:
  561. .. literalinclude:: Downstream/CMakeLists.txt
  562. :language: cmake
  563. :start-after: # use MathFunctions library
  564. To:
  565. .. literalinclude:: DownstreamComponents/CMakeLists.txt
  566. :language: cmake
  567. :start-after: # use MathFunctions library
  568. :end-before: # Workaround for GCC on AIX to avoid -isystem
  569. In ``main.cc``, replace ``#include MathFunctions.h`` with:
  570. .. literalinclude:: DownstreamComponents/main.cc
  571. :language: c
  572. :start-after: #include <string>
  573. :end-before: int main
  574. Finally, use the ``Addition`` library:
  575. .. literalinclude:: DownstreamComponents/main.cc
  576. :language: c
  577. :start-after: // calculate sum
  578. :end-before: return 0;
  579. Build the ``Downstream`` project and confirm that it can find and use the
  580. package components.