eclmist
eclmist

Reputation: 161

How to define a custom build configuration type where a target that is normally a .exe is instead a DLL

I'm using CMake to generate my Visual Studio solutions. Right now, CMake generates two configuration Release and Debug, under a single project. Both configs builds a win32 (.exe) application.

This works great, but I would also like to generate a third configuration, that builds a DLL instead. I'm aware that in CMake we can use add_library(LibraryName SHARED [files]) to generate a separate a project that creates builds a DLL target, but that is not what I want. Instead, I would like to generate a DLL configuration in visual studio, along side Debug and Release.

I can get the configuration by adding set(CMAKE_CONFIGURATION_TYPES Release Debug DLL) in CMakeList, but I'm not sure how to go about actually configuring it. How do I make this custom configuration actually build a DLL? If possible, I would also like to customize the output name and directory of this configuration, just like how I'm able to with CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE etc.

Is this possible? If so, how can it be done?

Upvotes: 4

Views: 2142

Answers (1)

Brecht Sanders
Brecht Sanders

Reputation: 7295

Instead of add_library(LibraryName SHARED [files]) you can keep the add_library(LibraryName [files]) without STATIC or SHARED and then you can run CMake with -DBUILD_SHARED_LIBS:BOOL=OFF or -DBUILD_SHARED_LIBS:BOOL=ON to build static or shared libraries respectively.

But that would require you to run CMake twice and compile twice.

To build both static and shared you can replace this in CMakeLists.txt:

add_library(LibraryName [files])

with:

add_library(LibraryName STATIC [files])
add_library(LibraryName_shared SHARED [files])
set_target_properties(LibraryName_shared PROPERTIES OUTPUT_NAME LibraryName)

You may also have to duplicate other lines (e.g. target_link_libraries and install) with the _shared target.

I use this method a lot to build static and shared libraries in one go for libraries whose CMakeLists.txt wasn't designed to do so.

As you're adding a separate target this way you should also be able to specify a separate output name and directory for it.

Upvotes: 1

Related Questions