CMake: How to use different ADD_EXECUTABLE for deb

2020-07-17 08:56发布

问题:

I'd like to build my application such that debug mode is a console application and release mode is a Win32 application. According to the documentation I need to add WIN32 to add_executable depending on whether I want a console application or not.

Because I'm using Visual Studio, I can't use CMAKE_BUILD_TYPE (the generated project contains multiple configurations). How can I tell CMAKE to use WIN32 for release builds and omit it for debug builds?

回答1:

Quoting http://www.cmake.org/Wiki/VSConfigSpecificSettings

if(WIN32)
   set_target_properties(WindowApplicationExample PROPERTIES LINK_FLAGS_DEBUG "/SUBSYSTEM:CONSOLE")
   set_target_properties(WindowApplicationExample PROPERTIES COMPILE_DEFINITIONS_DEBUG "_CONSOLE")
   set_target_properties(WindowApplicationExample PROPERTIES LINK_FLAGS_RELWITHDEBINFO "/SUBSYSTEM:CONSOLE")
   set_target_properties(WindowApplicationExample PROPERTIES COMPILE_DEFINITIONS_RELWITHDEBINFO "_CONSOLE")
   set_target_properties(WindowApplicationExample PROPERTIES LINK_FLAGS_RELEASE "/SUBSYSTEM:windows")
   set_target_properties(WindowApplicationExample PROPERTIES LINK_FLAGS_MINSIZEREL "/SUBSYSTEM:windows")
endif(WIN32)

UPDATE: This feature is broken in recent versions due to a bug. One workaround I've found is to specify "/SUBSYSTEM:windows" instead of "/SUBSYSTEM:WINDOWS". That seems to work for some reason.



回答2:

Dunno if this bug has been fixed in CMake yet. I'm using VC++ 2010 express and CMake v2.8.10.1 (which is currently the latest release) and I'm still having the exact same problem.

A working solution was provided here: modify your source code (e.g. main.cpp/main.c) by adding:

#ifndef NDEBUG
#pragma comment(linker, "/SUBSYSTEM:CONSOLE")
#endif

Alternatively, you could add the linker flag "/SUBSYSTEM:WINDOWS" to the release-mode build. I'm using this definition which seems to work:

#ifdef _MSC_VER
#    ifdef NDEBUG
#        pragma comment(linker, "/SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartup")
#    else
#        pragma comment(linker, "/SUBSYSTEM:CONSOLE")
#    endif
#endif

Use the entry-point setting in order to avoid linker errors in case you've defined:

int main(int argc, char* argv[]) { ... }