index.rst 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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. The :module:`GNUInstallDirs` module is included in order to provide the
  155. project with the flexibility to install into different platform layouts by
  156. making the directories available as cache variables.
  157. Create a library called ``MathFunctions`` with the :command:`add_library`
  158. command:
  159. .. literalinclude:: MathFunctions/CMakeLists.txt
  160. :language: cmake
  161. :start-after: # create library
  162. :end-before: # add include directories
  163. And then use the :command:`target_include_directories` command to specify the
  164. include directories for the target:
  165. .. literalinclude:: MathFunctions/CMakeLists.txt
  166. :language: cmake
  167. :start-after: # add include directories
  168. :end-before: # install the target and create export-set
  169. We need to tell CMake that we want to use different include directories
  170. depending on if we're building the library or using it from an installed
  171. location. If we don't do this, when CMake creates the export information it
  172. will export a path that is specific to the current build directory
  173. and will not be valid for other projects. We can use
  174. :manual:`generator expressions <cmake-generator-expressions(7)>` to specify
  175. that if we're building the library include the current source directory.
  176. Otherwise, when installed, include the ``include`` directory. See the `Creating
  177. Relocatable Packages`_ section for more details.
  178. The :command:`install(TARGETS)` and :command:`install(EXPORT)` commands
  179. work together to install both targets (a library in our case) and a CMake
  180. file designed to make it easy to import the targets into another CMake project.
  181. First, in the :command:`install(TARGETS)` command we will specify the target,
  182. the ``EXPORT`` name and the destinations that tell CMake where to install the
  183. targets.
  184. .. literalinclude:: MathFunctions/CMakeLists.txt
  185. :language: cmake
  186. :start-after: # install the target and create export-set
  187. :end-before: # install header file
  188. Here, the ``EXPORT`` option tells CMake to create an export called
  189. ``MathFunctionsTargets``. The generated :prop_tgt:`IMPORTED` targets have
  190. appropriate properties set to define their
  191. :ref:`usage requirements <Target Usage Requirements>`, such as
  192. :prop_tgt:`INTERFACE_INCLUDE_DIRECTORIES`,
  193. :prop_tgt:`INTERFACE_COMPILE_DEFINITIONS` and other relevant built-in
  194. ``INTERFACE_`` properties. The ``INTERFACE`` variant of user-defined
  195. properties listed in :prop_tgt:`COMPATIBLE_INTERFACE_STRING` and other
  196. :ref:`Compatible Interface Properties` are also propagated to the
  197. generated :prop_tgt:`IMPORTED` targets. For example, in this case, the
  198. :prop_tgt:`IMPORTED` target will have its
  199. :prop_tgt:`INTERFACE_INCLUDE_DIRECTORIES` property populated with
  200. the directory specified by the ``INCLUDES DESTINATION`` property. As a
  201. relative path was given, it is treated as relative to the
  202. :variable:`CMAKE_INSTALL_PREFIX`.
  203. Note, we have *not* asked CMake to install the export yet.
  204. We don't want to forget to install the ``MathFunctions.h`` header file with the
  205. :command:`install(FILES)` command. The header file should be installed to the
  206. ``include`` directory, as specified by the
  207. :command:`target_include_directories` command above.
  208. .. literalinclude:: MathFunctions/CMakeLists.txt
  209. :language: cmake
  210. :start-after: # install header file
  211. :end-before: # generate and install export file
  212. Now that the ``MathFunctions`` library and header file are installed, we also
  213. need to explicitly install the ``MathFunctionsTargets`` export details. Use
  214. the :command:`install(EXPORT)` command to export the targets in
  215. ``MathFunctionsTargets``, as defined by the :command:`install(TARGETS)`
  216. command.
  217. .. literalinclude:: MathFunctions/CMakeLists.txt
  218. :language: cmake
  219. :start-after: # generate and install export file
  220. :end-before: # include CMakePackageConfigHelpers macro
  221. This command generates the ``MathFunctionsTargets.cmake`` file and arranges
  222. to install it to ``lib/cmake``. The file contains code suitable for
  223. use by downstreams to import all targets listed in the install command from
  224. the installation tree.
  225. The ``NAMESPACE`` option will prepend ``MathFunctions::`` to the target names
  226. as they are written to the export file. This convention of double-colons
  227. gives CMake a hint that the name is an :prop_tgt:`IMPORTED` target when it
  228. is used by downstream projects. This way, CMake can issue a diagnostic
  229. message if the package providing it was not found.
  230. The generated export file contains code that creates an :prop_tgt:`IMPORTED` library.
  231. .. code-block:: cmake
  232. # Create imported target MathFunctions::MathFunctions
  233. add_library(MathFunctions::MathFunctions STATIC IMPORTED)
  234. set_target_properties(MathFunctions::MathFunctions PROPERTIES
  235. INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
  236. )
  237. This code is very similar to the example we created by hand in the
  238. `Importing Libraries`_ section. Note that ``${_IMPORT_PREFIX}`` is computed
  239. relative to the file location.
  240. An outside project may load this file with the :command:`include` command and
  241. reference the ``MathFunctions`` library from the installation tree as if it
  242. were built in its own tree. For example:
  243. .. code-block:: cmake
  244. :linenos:
  245. include(${INSTALL_PREFIX}/lib/cmake/MathFunctionTargets.cmake)
  246. add_executable(myexe src1.c src2.c )
  247. target_link_libraries(myexe PRIVATE MathFunctions::MathFunctions)
  248. Line 1 loads the target CMake file. Although we only exported a single
  249. target, this file may import any number of targets. Their locations are
  250. computed relative to the file location so that the install tree may be
  251. easily moved. Line 3 references the imported ``MathFunctions`` library. The
  252. resulting build system will link to the library from its installed location.
  253. Executables may also be exported and imported using the same process.
  254. Any number of target installations may be associated with the same
  255. export name. Export names are considered global so any directory may
  256. contribute a target installation. The :command:`install(EXPORT)` command only
  257. needs to be called once to install a file that references all targets. Below
  258. is an example of how multiple exports may be combined into a single
  259. export file, even if they are in different subdirectories of the project.
  260. .. code-block:: cmake
  261. # A/CMakeLists.txt
  262. add_executable(myexe src1.c)
  263. install(TARGETS myexe DESTINATION lib/myproj
  264. EXPORT myproj-targets)
  265. # B/CMakeLists.txt
  266. add_library(foo STATIC foo1.c)
  267. install(TARGETS foo DESTINATION lib EXPORTS myproj-targets)
  268. # Top CMakeLists.txt
  269. add_subdirectory (A)
  270. add_subdirectory (B)
  271. install(EXPORT myproj-targets DESTINATION lib/myproj)
  272. Creating Packages
  273. -----------------
  274. At this point, the ``MathFunctions`` project is exporting the target
  275. information required to be used by other projects. We can make this project
  276. even easier for other projects to use by generating a configuration file so
  277. that the CMake :command:`find_package` command can find our project.
  278. To start, we will need to make a few additions to the ``CMakeLists.txt``
  279. file. First, include the :module:`CMakePackageConfigHelpers` module to get
  280. access to some helper functions for creating config files.
  281. .. literalinclude:: MathFunctions/CMakeLists.txt
  282. :language: cmake
  283. :start-after: # include CMakePackageConfigHelpers macro
  284. :end-before: # set version
  285. Then we will create a package configuration file and a package version file.
  286. Creating a Package Configuration File
  287. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  288. Use the :command:`configure_package_config_file` command provided by the
  289. :module:`CMakePackageConfigHelpers` to generate the package configuration
  290. file. Note that this command should be used instead of the plain
  291. :command:`configure_file` command. It helps to ensure that the resulting
  292. package is relocatable by avoiding hardcoded paths in the installed
  293. configuration file. The path given to ``INSTALL_DESTINATION`` must be the
  294. destination where the ``MathFunctionsConfig.cmake`` file will be installed.
  295. We will examine the contents of the package configuration file in the next
  296. section.
  297. .. literalinclude:: MathFunctions/CMakeLists.txt
  298. :language: cmake
  299. :start-after: # create config file
  300. :end-before: # install config files
  301. Install the generated configuration files with the :command:`INSTALL(files)`
  302. command. Both ``MathFunctionsConfigVersion.cmake`` and
  303. ``MathFunctionsConfig.cmake`` are installed to the same location, completing
  304. the package.
  305. .. literalinclude:: MathFunctions/CMakeLists.txt
  306. :language: cmake
  307. :start-after: # install config files
  308. :end-before: # generate the export targets for the build tree
  309. Now we need to create the package configuration file itself. In this case, the
  310. ``Config.cmake.in`` file is very simple but sufficient to allow downstreams
  311. to use the :prop_tgt:`IMPORTED` targets.
  312. .. literalinclude:: MathFunctions/Config.cmake.in
  313. The first line of the file contains only the string ``@PACKAGE_INIT@``. This
  314. expands when the file is configured and allows the use of relocatable paths
  315. prefixed with ``PACKAGE_``. It also provides the ``set_and_check()`` and
  316. ``check_required_components()`` macros.
  317. The ``check_required_components`` helper macro ensures that all requested,
  318. non-optional components have been found by checking the
  319. ``<Package>_<Component>_FOUND`` variables for all required components. This
  320. macro should be called at the end of the package configuration file even if the
  321. package does not have any components. This way, CMake can make sure that the
  322. downstream project hasn't specified any non-existent components. If
  323. ``check_required_components`` fails, the ``<Package>_FOUND`` variable is set to
  324. FALSE, and the package is considered to be not found.
  325. The ``set_and_check()`` macro should be used in configuration files instead
  326. of the normal ``set()`` command for setting directories and file locations.
  327. If a referenced file or directory does not exist, the macro will fail.
  328. If any macros should be provided by the ``MathFunctions`` package, they should
  329. be in a separate file which is installed to the same location as the
  330. ``MathFunctionsConfig.cmake`` file, and included from there.
  331. **All required dependencies of a package must also be found in the package
  332. configuration file.** Let's imagine that we require the ``Stats`` library in
  333. our project. In the CMakeLists file, we would add:
  334. .. code-block:: cmake
  335. find_package(Stats 2.6.4 REQUIRED)
  336. target_link_libraries(MathFunctions PUBLIC Stats::Types)
  337. As the ``Stats::Types`` target is a ``PUBLIC`` dependency of ``MathFunctions``,
  338. downstreams must also find the ``Stats`` package and link to the
  339. ``Stats::Types`` library. The ``Stats`` package should be found in the
  340. configuration file to ensure this.
  341. .. code-block:: cmake
  342. include(CMakeFindDependencyMacro)
  343. find_dependency(Stats 2.6.4)
  344. The ``find_dependency`` macro from the :module:`CMakeFindDependencyMacro`
  345. module helps by propagating whether the package is ``REQUIRED``, or
  346. ``QUIET``, etc. The ``find_dependency`` macro also sets
  347. ``MathFunctions_FOUND`` to ``False`` if the dependency is not found, along
  348. with a diagnostic that the ``MathFunctions`` package cannot be used without
  349. the ``Stats`` package.
  350. **Exercise:** Add a required library to the ``MathFunctions`` project.
  351. Creating a Package Version File
  352. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  353. The :module:`CMakePackageConfigHelpers` module provides the
  354. :command:`write_basic_package_version_file` command for creating a simple
  355. package version file. This file is read by CMake when :command:`find_package`
  356. is called to determine the compatibility with the requested version, and to set
  357. some version-specific variables such as ``<PackageName>_VERSION``,
  358. ``<PackageName>_VERSION_MAJOR``, ``<PackageName>_VERSION_MINOR``, etc. See
  359. :manual:`cmake-packages <cmake-packages(7)>` documentation for more details.
  360. .. literalinclude:: MathFunctions/CMakeLists.txt
  361. :language: cmake
  362. :start-after: # set version
  363. :end-before: # create config file
  364. In our example, ``MathFunctions_MAJOR_VERSION`` is defined as a
  365. :prop_tgt:`COMPATIBLE_INTERFACE_STRING` which means that it must be
  366. compatible among the dependencies of any depender. By setting this
  367. custom defined user property in this version and in the next version of
  368. ``MathFunctions``, :manual:`cmake <cmake(1)>` will issue a diagnostic if
  369. there is an attempt to use version 3 together with version 4. Packages can
  370. choose to employ such a pattern if different major versions of the package
  371. are designed to be incompatible.
  372. Exporting Targets from the Build Tree
  373. -------------------------------------
  374. Typically, projects are built and installed before being used by an outside
  375. project. However, in some cases, it is desirable to export targets directly
  376. from a build tree. The targets may then be used by an outside project that
  377. references the build tree with no installation involved. The :command:`export`
  378. command is used to generate a file exporting targets from a project build tree.
  379. If we want our example project to also be used from a build directory we only
  380. have to add the following to ``CMakeLists.txt``:
  381. .. literalinclude:: MathFunctions/CMakeLists.txt
  382. :language: cmake
  383. :start-after: # generate the export targets for the build tree
  384. Here we use the :command:`export` command to generate the export targets for
  385. the build tree. In this case, we'll create a file called
  386. ``MathFunctionsTargets.cmake`` in the ``cmake`` subdirectory of the build
  387. directory. The generated file contains the required code to import the target
  388. and may be loaded by an outside project that is aware of the project build
  389. tree. This file is specific to the build-tree, and **is not relocatable**.
  390. It is possible to create a suitable package configuration file and package
  391. version file to define a package for the build tree which may be used without
  392. installation. Consumers of the build tree can simply ensure that the
  393. :variable:`CMAKE_PREFIX_PATH` contains the build directory, or set the
  394. ``MathFunctions_DIR`` to ``<build_dir>/MathFunctions`` in the cache.
  395. An example application of this feature is for building an executable on a host
  396. platform when cross-compiling. The project containing the executable may be
  397. built on the host platform and then the project that is being cross-compiled
  398. for another platform may load it.
  399. Building and Installing a Package
  400. ---------------------------------
  401. At this point, we have generated a relocatable CMake configuration for our
  402. project that can be used after the project has been installed. Let's try to
  403. build the ``MathFunctions`` project:
  404. .. code-block:: console
  405. mkdir MathFunctions_build
  406. cd MathFunctions_build
  407. cmake ../MathFunctions
  408. cmake --build .
  409. In the build directory, notice that the file ``MathFunctionsTargets.cmake``
  410. has been created in the ``cmake`` subdirectory.
  411. Now install the project:
  412. .. code-block:: console
  413. $ cmake --install . --prefix "/home/myuser/installdir"
  414. Creating Relocatable Packages
  415. =============================
  416. Packages created by :command:`install(EXPORT)` are designed to be relocatable,
  417. using paths relative to the location of the package itself. They must not
  418. reference absolute paths of files on the machine where the package is built
  419. that will not exist on the machines where the package may be installed.
  420. When defining the interface of a target for ``EXPORT``, keep in mind that the
  421. include directories should be specified as relative paths to the
  422. :variable:`CMAKE_INSTALL_PREFIX` but should not explicitly include the
  423. :variable:`CMAKE_INSTALL_PREFIX`:
  424. .. code-block:: cmake
  425. target_include_directories(tgt INTERFACE
  426. # Wrong, not relocatable:
  427. $<INSTALL_INTERFACE:${CMAKE_INSTALL_PREFIX}/include/TgtName>
  428. )
  429. target_include_directories(tgt INTERFACE
  430. # Ok, relocatable:
  431. $<INSTALL_INTERFACE:include/TgtName>
  432. )
  433. The ``$<INSTALL_PREFIX>``
  434. :manual:`generator expression <cmake-generator-expressions(7)>` may be used as
  435. a placeholder for the install prefix without resulting in a non-relocatable
  436. package. This is necessary if complex generator expressions are used:
  437. .. code-block:: cmake
  438. target_include_directories(tgt INTERFACE
  439. # Ok, relocatable:
  440. $<INSTALL_INTERFACE:$<INSTALL_PREFIX>/include/TgtName>
  441. )
  442. This also applies to paths referencing external dependencies.
  443. It is not advisable to populate any properties which may contain
  444. paths, such as :prop_tgt:`INTERFACE_INCLUDE_DIRECTORIES` or
  445. :prop_tgt:`INTERFACE_LINK_LIBRARIES`, with paths relevant to dependencies.
  446. For example, this code may not work well for a relocatable package:
  447. .. code-block:: cmake
  448. target_link_libraries(MathFunctions INTERFACE
  449. ${Foo_LIBRARIES} ${Bar_LIBRARIES}
  450. )
  451. target_include_directories(MathFunctions INTERFACE
  452. "$<INSTALL_INTERFACE:${Foo_INCLUDE_DIRS};${Bar_INCLUDE_DIRS}>"
  453. )
  454. The referenced variables may contain the absolute paths to libraries
  455. and include directories **as found on the machine the package was made on**.
  456. This would create a package with hard-coded paths to dependencies not
  457. suitable for relocation.
  458. Ideally such dependencies should be used through their own
  459. :ref:`IMPORTED targets <Imported Targets>` that have their own
  460. :prop_tgt:`IMPORTED_LOCATION` and usage requirement properties
  461. such as :prop_tgt:`INTERFACE_INCLUDE_DIRECTORIES` populated
  462. appropriately. Those imported targets may then be used with
  463. the :command:`target_link_libraries` command for ``MathFunctions``:
  464. .. code-block:: cmake
  465. target_link_libraries(MathFunctions INTERFACE Foo::Foo Bar::Bar)
  466. With this approach the package references its external dependencies
  467. only through the names of :ref:`IMPORTED targets <Imported Targets>`.
  468. When a consumer uses the installed package, the consumer will run the
  469. appropriate :command:`find_package` commands (via the ``find_dependency``
  470. macro described above) to find the dependencies and populate the
  471. imported targets with appropriate paths on their own machine.
  472. Using the Package Configuration File
  473. ====================================
  474. Now we're ready to create a project to use the installed ``MathFunctions``
  475. library. In this section we will be using source code from
  476. ``Help\guide\importing-exporting\Downstream``. In this directory, there is a
  477. source file called ``main.cc`` that uses the ``MathFunctions`` library to
  478. calculate the square root of a given number and then prints the results:
  479. .. literalinclude:: Downstream/main.cc
  480. :language: c++
  481. As before, we'll start with the :command:`cmake_minimum_required` and
  482. :command:`project` commands in the ``CMakeLists.txt`` file. For this project,
  483. we'll also specify the C++ standard.
  484. .. literalinclude:: Downstream/CMakeLists.txt
  485. :language: cmake
  486. :end-before: # find MathFunctions
  487. We can use the :command:`find_package` command:
  488. .. literalinclude:: Downstream/CMakeLists.txt
  489. :language: cmake
  490. :start-after: # find MathFunctions
  491. :end-before: # create executable
  492. Create an executable:
  493. .. literalinclude:: Downstream/CMakeLists.txt
  494. :language: cmake
  495. :start-after: # create executable
  496. :end-before: # use MathFunctions library
  497. And link to the ``MathFunctions`` library:
  498. .. literalinclude:: Downstream/CMakeLists.txt
  499. :language: cmake
  500. :start-after: # use MathFunctions library
  501. That's it! Now let's try to build the ``Downstream`` project.
  502. .. code-block:: console
  503. mkdir Downstream_build
  504. cd Downstream_build
  505. cmake ../Downstream
  506. cmake --build .
  507. A warning may have appeared during CMake configuration:
  508. .. code-block:: console
  509. CMake Warning at CMakeLists.txt:4 (find_package):
  510. By not providing "FindMathFunctions.cmake" in CMAKE_MODULE_PATH this
  511. project has asked CMake to find a package configuration file provided by
  512. "MathFunctions", but CMake did not find one.
  513. Could not find a package configuration file provided by "MathFunctions"
  514. with any of the following names:
  515. MathFunctionsConfig.cmake
  516. mathfunctions-config.cmake
  517. Add the installation prefix of "MathFunctions" to CMAKE_PREFIX_PATH or set
  518. "MathFunctions_DIR" to a directory containing one of the above files. If
  519. "MathFunctions" provides a separate development package or SDK, be sure it
  520. has been installed.
  521. Set the ``CMAKE_PREFIX_PATH`` to where MathFunctions was installed previously
  522. and try again. Ensure that the newly created executable runs as expected.
  523. Adding Components
  524. =================
  525. Let's edit the ``MathFunctions`` project to use components. The source code for
  526. this section can be found in
  527. ``Help\guide\importing-exporting\MathFunctionsComponents``. The CMakeLists file
  528. for this project adds two subdirectories: ``Addition`` and ``SquareRoot``.
  529. .. literalinclude:: MathFunctionsComponents/CMakeLists.txt
  530. :language: cmake
  531. :end-before: # include CMakePackageConfigHelpers macro
  532. Generate and install the package configuration and package version files:
  533. .. literalinclude:: MathFunctionsComponents/CMakeLists.txt
  534. :language: cmake
  535. :start-after: # include CMakePackageConfigHelpers macro
  536. If ``COMPONENTS`` are specified when the downstream uses
  537. :command:`find_package`, they are listed in the
  538. ``<PackageName>_FIND_COMPONENTS`` variable. We can use this variable to verify
  539. that all necessary component targets are included in ``Config.cmake.in``. At
  540. the same time, this function will act as a custom ``check_required_components``
  541. macro to ensure that the downstream only attempts to use supported components.
  542. .. literalinclude:: MathFunctionsComponents/Config.cmake.in
  543. Here, the ``MathFunctions_NOT_FOUND_MESSAGE`` is set to a diagnosis that the
  544. package could not be found because an invalid component was specified. This
  545. message variable can be set for any case where the ``_FOUND`` variable is set
  546. to ``False``, and will be displayed to the user.
  547. The ``Addition`` and ``SquareRoot`` directories are similar. Let's look at one
  548. of the CMakeLists files:
  549. .. literalinclude:: MathFunctionsComponents/SquareRoot/CMakeLists.txt
  550. :language: cmake
  551. Now we can build the project as described in earlier sections. To test using
  552. this package, we can use the project in
  553. ``Help\guide\importing-exporting\DownstreamComponents``. There's two
  554. differences from the previous ``Downstream`` project. First, we need to find
  555. the package components. Change the ``find_package`` line from:
  556. .. literalinclude:: Downstream/CMakeLists.txt
  557. :language: cmake
  558. :start-after: # find MathFunctions
  559. :end-before: # create executable
  560. To:
  561. .. literalinclude:: DownstreamComponents/CMakeLists.txt
  562. :language: cmake
  563. :start-after: # find MathFunctions
  564. :end-before: # create executable
  565. and the ``target_link_libraries`` line from:
  566. .. literalinclude:: Downstream/CMakeLists.txt
  567. :language: cmake
  568. :start-after: # use MathFunctions library
  569. To:
  570. .. literalinclude:: DownstreamComponents/CMakeLists.txt
  571. :language: cmake
  572. :start-after: # use MathFunctions library
  573. :end-before: # Workaround for GCC on AIX to avoid -isystem
  574. In ``main.cc``, replace ``#include MathFunctions.h`` with:
  575. .. literalinclude:: DownstreamComponents/main.cc
  576. :language: c
  577. :start-after: #include <string>
  578. :end-before: int main
  579. Finally, use the ``Addition`` library:
  580. .. literalinclude:: DownstreamComponents/main.cc
  581. :language: c
  582. :start-after: // calculate sum
  583. :end-before: return 0;
  584. Build the ``Downstream`` project and confirm that it can find and use the
  585. package components.