How do you set properties in a vcproj file with cm

2020-07-14 10:08发布

问题:

vcproj files for Visual Studio contain various settings or properties which affect the build. For instance, a few of the ones that a project that I'm trying to convert to cmake uses are

StringPooling="true"
RuntimeLibrary="2"
TreatWChar_tAsBuiltInType="true"
WarningLevel="3"
Detect64BitPortabilityProblems="false"

There are of course plenty of others that could be set. The question is how to set them when the project is generated using cmake. Does anyone have any idea how to set these sort of properties when using cmake other than editing the vcproj file after the fact? I can't find anything explaining how these sort of properties might be set via cmake. The only ones that I know how to set are ones that cmake specifically has cross-platform stuff for (e.g. PreprocessorDefinitions or AdditionalIncludeDirectories). But I need to be able to set ones that are specific to Visual Studio.

回答1:

For the flags you've listed, you'd add the following to your CMakeLists.txt:

if(MSVC)
  # StringPooling: true == /GF  false == /GF-
  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /GF")

  # RuntimeLibrary
  # 0 (MultiThreaded) == /MT
  # 1 (MultiThreadedDebug) == /MTd
  # 2 (MultiThreadedDLL) == /MD
  # 3 (MultiThreadedDebugDLL) == /MDd
  set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MD")
  set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MDd")

  # TreatWChar_tAsBuiltInType: true == /Zc:wchar_t  false == /Zc:wchar_t-
  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /Zc:wchar_t")

  # WarningLevel: /W<level 0 to 4> or /Wall
  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W3")

  # Detect64BitPortabilityProblems: /Wp64 - Deprecated since VC++ 2010 
  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /Wp64")
endif()

You can group these in one call if you want:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /GF /Zc:wchar_t /W3 /Wp64")

If you only need to add a flag to a single target (say, MyTestExe), you can do:

set_target_properties(MyTestExe PROPERTIES COMPILE_FLAGS "/GF- /W2")

Options set via this target-specific method will override any conflicting ones in the general CMAKE_CXX_FLAGS variable.

For further info on these commands do:

cmake --help-variable "CMAKE_<LANG>_FLAGS_DEBUG"
cmake --help-command set_target_properties
cmake --help-property COMPILE_FLAGS

The Visual Studio compiler options are listed here.



回答2:

Each of these properties corresponds to a command-line option of the compiler (cl). You set these command line options in your CMakeList (using variables like CMAKE_CXX_FLAGS, commands like add_definitions() and properties like COMPILE_FLAGS) and CMake automatically translates them to the settings in .vc[x]proj files when generating them. Those it does not understand are just added as "Additional command-line options".