KasperskyOS Community Edition

Building dynamic libraries

May 21, 2024

ID shared_libraries_building

When building dynamic libraries, you must use a toolchain that supports dynamic linking.

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

add_library(<build target name> SHARED [list of paths to files of the library source code])

Use of this CMake command results in an error if the toolchain does not support dynamic linking.

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

add_library(<build target name> [list of paths to files 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")

# The PLATFORM_SUPPORTS_DYNAMIC_LINKING variable has the

# value "true" when using dynamic

# linking. If initialize_platform(FORCE_STATIC) is called,

# this variable has the value "false".

if(PLATFORM_SUPPORTS_DYNAMIC_LINKING)

# Build the dynamic library

add_library(somelib_shared SHARED src/somesrc.cpp)

set_target_properties(somelib_shared PROPERTIES OUTPUT_NAME "somelib")

endif()

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 <list of names of build targets> PROPERTY POSITION_INDEPENDENT_CODE ON)

Did you find this article helpful?
What can we do better?
Thank you for your feedback! You're helping us improve.
Thank you for your feedback! You're helping us improve.