cmake: add “d” suffix for debug build of static li

2020-02-29 01:54发布

问题:

I would like to implement a naming scheme for libraries similar to the one mentioned here: Library name for x32 vs x64

The CMakeLists.txt file is setup to create a static library

add_library(test test.h test.cpp)

After creating a visual studio solution from the cmake lists the project is set up in such a way that the debug library test.lib is written to /x64/Debug/test.lib and the release version is written to /x64/Release/test.lib. I would prefer to write them both to /lib/ but append a "d" to the debug version. The idea is to get

/lib/test.lib
/lib/testd.lib

and if possible have an additional suffix for 64 bit builds to get

/lib/test.lib
/lib/test64.lib
/lib/testd.lib
/lib/test64d.lib

Is there a straightforward way to do this?


Edit: this can be used later nicely in the project using the libs like this: Linking different libraries for Debug and Release builds in Cmake on windows?


Edit: I had problems removing the Debug and Release folders from the output, which can be fixed by this answer: How to not add Release or Debug to output path?

回答1:

CMAKE_DEBUG_POSTFIX is used for appending the d for debug libraries:

set(CMAKE_DEBUG_POSTFIX d)

If you do not want to set this globally, you can also use the DEBUG_POSTFIX target property instead on selected libraries.

There is no corresponding feature for distinguishing 32/64 bit builds, but since it is impossible to mix those two in the same CMake configuration, you can easily distinguish those cases manually, e.g.

if(CMAKE_SIZEOF_VOID_P EQUAL 4)
    set(ARCH_POSTFIX "")
else()
    set(ARCH_POSTFIX 64)
endif()

add_library(my_lib${ARCH_POSTFIX} [...])

Or, if you want to use the same target name on the different architectures, set a variable like CMAKE_STATIC_LIBRARY_SUFFIX (there exist a whole bunch of them, so you can select the correct one for your target type and based on which output files you want to append a suffix to).

And since you also mentioned this answer for finding such libraries: Prefer using imported targets instead of the coarse-grained legacy debug and optimized qualifiers for target_link_libraries. Config file packages provide a convenient way of exposing such imported targets to your clients, and they also handle any suffix shenanigans automatically for you.