Project build configuration in CMake

2019-02-10 21:01发布

问题:

My question is very similar to CMake : Changing name of Visual Studio and Xcode exectuables depending on configuration in a project generated by CMake. In that post the output file name will change according to the project configuration (Debug, Release and so on). I want to go further. When I know the configuration of the project, I want to tell the executable program to link different library names depending on project configurations. I was wondering whether there is a variable in CMake that can tell the project configuration. If there exists such a variable, my task will become easier:

if (Project_Configure_Name STREQUAL "Debug")
   #do some thing
elseif (Project_Configure_Name STREQUAL "Release")
   #do some thing
endif()

回答1:

According to http://cmake.org/cmake/help/v2.8.8/cmake.html#command:target_link_libraries, you can specify libraries according to the configurations, for example:

target_link_libraries(mytarget
  debug      mydebuglibrary
  optimized  myreleaselibrary
)

Be careful that the optimized mode means every configuration that is not debug.

Following is a more complicated but more controllable solution:

Assuming you are linking to an imported library (not compiled in your cmake project), you can add it using:

add_library(foo STATIC IMPORTED)
set_property(TARGET foo PROPERTY IMPORTED_LOCATION_RELEASE c:/path/to/foo.lib)
set_property(TARGET foo PROPERTY IMPORTED_LOCATION_DEBUG   c:/path/to/foo_d.lib)
add_executable(myexe src1.c src2.c)
target_link_libraries(myexe foo)

See http://www.cmake.org/Wiki/CMake/Tutorials/Exporting_and_Importing_Targets for more details.



回答2:

There is always another way:

  if(CMAKE_BUILD_TYPE MATCHES "release")

    SET(CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE})

  else(CMAKE_BUILD_TYPE MATCHES "debug")

     SET(CMAKE_BUILD_TYPE "debug")

   endif(CMAKE_BUILD_TYPE MATCHES "release")

We can use the variable CMAKE_BUILD_TYPE. We can also change this variable at the beginning of invoking CMAKE:

cmake .. -DCMAKE_BUILD_TYPE:STRING=debug

Then we can use this variable as an indicator of build configuration.



标签: cmake