Building dynamic libraries

To build a dynamic library, you need to use the following CMake command:

add_library(<build target name> SHARED <path to a file of the library source code>…)

You can also build a dynamic library by using the following CMake command:

add_library(<build target name> <path to a file of the library source code>…)

The cmake shell command must be called with the -D BUILD_SHARED_LIBS=YES parameter. (If the cmake shell command is called without the -D BUILD_SHARED_LIBS=YES parameter, a static library will be built.)

Example:

#!/bin/bash

cmake -G "Unix Makefiles" \

-D CMAKE_BUILD_TYPE:STRING=Debug \

-D CMAKE_TOOLCHAIN_FILE=$SDK_PREFIX/toolchain/share/toolchain-$TARGET.cmake \

-D BUILD_SHARED_LIBS=YES \

-B build \

&& cmake --build build --target kos-image

By default, the library file name matches the name of the build target defined via the parameter of the CMake add_library() command. The library file name can be changed by using the CMake set_target_properties() command. This can be done to make the library file name identical for its dynamic and static variants.

Example:

# Build the static library

add_library(somelib_static STATIC src/somesrc.cpp)

set_target_properties(somelib_static PROPERTIES OUTPUT_NAME "somelib")

# Build the dynamic library

add_library(somelib_shared SHARED src/somesrc.cpp)

set_target_properties(somelib_shared PROPERTIES OUTPUT_NAME "somelib")

A dynamic library can be linked to other static and dynamic libraries by using the CMake target_link_libraries() command. In this case, static libraries must be built with the -fPIC flag. This flag is applied when building a static library if the following CMake command is used:

set_property(TARGET <build target name>… PROPERTY POSITION_INDEPENDENT_CODE ON)

Page top