How does the CMake project specify c++ language standards in VS2019

  • 2020-07-21 09:25:41
  • OfStack

How does the CMake project specify language standards in VS2019

A few days ago, the blogger used c++17 to bind the new feature structure. The code is as follows:


#include<bits/stdc++.h>
using namespace std;
int main() {
  unordered_map<int, int> mmid;
  for (auto [a, b] : mmid) {
    cout << a << ' ' << b << endl;
  }
  return 0;
}

Later, I checked 1 and found that the default c++ language standard for CMake project was lower than 17, so I had to specify 1 language version.

There are two ways to set it up. The first can be set to use the latest language standards by default. Add the following code to the CMakeLists.txt file.


if (MSVC_VERSION GREATER_EQUAL "1900")
  include(CheckCXXCompilerFlag)
  CHECK_CXX_COMPILER_FLAG("/std:c++latest" _cpp_latest_flag_supported)
  if (_cpp_latest_flag_supported)
    add_compile_options("/std:c++latest")
  endif()
endif()

The above method is too tedious, but it doesn't matter that there is a second, simpler method, which only takes 1 line of code.

[

set(CMAKE_CXX_STANDARD 17)

]

This makes it possible to use the standard c++17. If you want to use another version of the language annotation, replace the 17 with the corresponding version.

PS: Note in particular that the appellate code 1 must be placed at the beginning of the CMakeLists file, otherwise it is invalid.

cmake specifies the compiled version of c++

Modify the CMakeLists.txt file to add the following command

[

SET(CMAKE_C_COMPILER "/home/public/local/bin/gcc")

SET(CMAKE_CXX_COMPILER "/home/public/local/bin/g++")

]

Cmake is compiled using C++11

The cmake compiler project requires support for the C++11 feature, just add it to CMakeLists.txt:

[

add_definitions(-std=c++11)

]

Related articles: