index.rst 30 KB

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