2022-11-16 20:14:03 +01:00
|
|
|
Step 10: Selecting Static or Shared Libraries
|
|
|
|
=============================================
|
2021-09-14 00:13:48 +02:00
|
|
|
|
|
|
|
In this section we will show how the :variable:`BUILD_SHARED_LIBS` variable can
|
|
|
|
be used to control the default behavior of :command:`add_library`,
|
|
|
|
and allow control over how libraries without an explicit type (``STATIC``,
|
|
|
|
``SHARED``, ``MODULE`` or ``OBJECT``) are built.
|
|
|
|
|
|
|
|
To accomplish this we need to add :variable:`BUILD_SHARED_LIBS` to the
|
|
|
|
top-level ``CMakeLists.txt``. We use the :command:`option` command as it allows
|
|
|
|
users to optionally select if the value should be ``ON`` or ``OFF``.
|
|
|
|
|
2022-11-16 20:14:03 +01:00
|
|
|
.. literalinclude:: Step11/CMakeLists.txt
|
2021-09-14 00:13:48 +02:00
|
|
|
:caption: CMakeLists.txt
|
|
|
|
:name: CMakeLists.txt-option-BUILD_SHARED_LIBS
|
|
|
|
:language: cmake
|
2023-07-02 19:51:09 +02:00
|
|
|
:start-after: set(CMAKE_RUNTIME_OUTPUT_DIRECTORY
|
|
|
|
:end-before: # configure a header file to pass the version number only
|
2021-09-14 00:13:48 +02:00
|
|
|
|
2023-07-02 19:51:09 +02:00
|
|
|
Next, we need to specify output directories for our static and shared
|
|
|
|
libraries.
|
2021-09-14 00:13:48 +02:00
|
|
|
|
2023-07-02 19:51:09 +02:00
|
|
|
.. literalinclude:: Step11/CMakeLists.txt
|
|
|
|
:caption: CMakeLists.txt
|
|
|
|
:name: CMakeLists.txt-cmake-output-directories
|
2021-09-14 00:13:48 +02:00
|
|
|
:language: cmake
|
2023-07-02 19:51:09 +02:00
|
|
|
:start-after: # we don't need to tinker with the path to run the executable
|
|
|
|
:end-before: # configure a header file to pass the version number only
|
2021-09-14 00:13:48 +02:00
|
|
|
|
|
|
|
Finally, update ``MathFunctions/MathFunctions.h`` to use dll export defines:
|
|
|
|
|
2022-11-16 20:14:03 +01:00
|
|
|
.. literalinclude:: Step11/MathFunctions/MathFunctions.h
|
2021-09-14 00:13:48 +02:00
|
|
|
:caption: MathFunctions/MathFunctions.h
|
|
|
|
:name: MathFunctions/MathFunctions.h
|
|
|
|
:language: c++
|
|
|
|
|
|
|
|
At this point, if you build everything, you may notice that linking fails
|
|
|
|
as we are combining a static library without position independent code with a
|
|
|
|
library that has position independent code. The solution to this is to
|
|
|
|
explicitly set the :prop_tgt:`POSITION_INDEPENDENT_CODE` target property of
|
2023-05-23 16:38:00 +02:00
|
|
|
SqrtLibrary to be ``True`` when building shared libraries.
|
2021-09-14 00:13:48 +02:00
|
|
|
|
2022-11-16 20:14:03 +01:00
|
|
|
.. literalinclude:: Step11/MathFunctions/CMakeLists.txt
|
2021-09-14 00:13:48 +02:00
|
|
|
:caption: MathFunctions/CMakeLists.txt
|
|
|
|
:name: MathFunctions/CMakeLists.txt-POSITION_INDEPENDENT_CODE
|
|
|
|
:language: cmake
|
|
|
|
:lines: 37-42
|
|
|
|
|
|
|
|
**Exercise**: We modified ``MathFunctions.h`` to use dll export defines.
|
|
|
|
Using CMake documentation can you find a helper module to simplify this?
|