Building a library as BOTH as a shared library and as and archive?

I can force a library to be built as an archive by specifying: -DBUILD_SHARED_LIBS=OFF but how can I force it to be built as a both a static library and a dynamic library?

Thanks
David

It’s definitely possible, either by creating two targets (mylib_static and mylib_shared) or by invoking CMake twice, but I’m not sure these are the cleanest solutions available…

CMake doesn’t provide this out-of-the-box.

To get shared and static library, there needs to be created two separate libraries using add_library() or using a single add_library() but build the project twice (once with BUILD_SHARED_LIBS and next one without).

The main issue is many times heavily connected to the position independent code and the -fPIC flags. Shared libraries in most cases require the -fPIC, while static libraries and executables don’t necessary require it in many cases to squeeze a slight better performance out of the built files.

This can become especially complicated for complex projects that split code into several subdirectories using add_library() and then build the final produced item - either an executable or some main project-wide library out of those subdirectories.

A very basic example:

# CMakeLists.txt
cmake_minimum_required(VERSION 3.25...3.31)

project(TestingSharedAndStaticLibrary)

# Setting a list of source files:
set(
  sources
    foo_1.c
    foo_2.c
    foo_3.c
)

# STATIC library:
add_library(foo_static STATIC)
target_sources(foo_static PRIVATE ${sources})

# SHARED library:
add_library(foo_shared SHARED)
target_sources(foo_shared PRIVATE ${sources})

BTW, I’m facing exactly the same issue for quite a while now and still haven’t found a proper way how to do solve this issue without building the software twice or without too many build steps. There are also many advice out there to not duplicate the add_library() calls and that package should be built 2 times separately - one build for getting a static library and one build for getting a shared library, but after considering the end-user usability of the package as a whole, creating separate libraries seems to me a bit better solution for the time being here, I believe. At lease for my case. And I might be wrong though.