如何通过CMake target_compile_feature确保支持std::make_unique?
cxx_make_unique Not Working with target_compile_feature Ah, I’ve run into this exact confusion before! The problem here is that cxx_make_unique isn’t a valid compile feature identifier recognized by CMake. Let me break down why this happens and how to properly ensure your project supports std::make_unique.
Why Your Current Code Fails
CMake’s target_compile_features relies on a predefined set of feature identifiers that map to compiler-specific flags or standard requirements. std::make_unique was introduced in C14, but CMake doesn’t have a dedicated cxx_make_unique feature entry—instead, this functionality is bundled into the broader C14 standard support.
Correct Ways to Enable std::make_unique
You have two straightforward, reliable options to guarantee your project can use std::make_unique:
Option 1: Use
cxx_std_14withtarget_compile_features
This tells CMake to enable C++14 (or higher) support for your target, which includesstd::make_uniqueby default:target_compile_features(target_name PRIVATE cxx_std_14)The
PRIVATEkeyword ensures this setting only applies to your target’s own compilation (adjust toPUBLICorINTERFACEif you need to propagate it to dependent targets).Option 2: Set the C++ Standard Directly via Target Properties
If you prefer explicit control over the C++ standard version, useset_target_properties:set_target_properties(target_name PROPERTIES CXX_STANDARD 14 CXX_STANDARD_REQUIRED ON # Forces the compiler to use at least C++14 CXX_EXTENSIONS OFF # Disables non-standard compiler extensions (optional but recommended) )This approach makes your standard requirement crystal clear and works across all modern compilers.
Bonus: Checking for std::make_unique Explicitly (If Needed)
While it’s unnecessary for most cases, if you want to verify std::make_unique support without enforcing the entire C++14 standard, you can use CMake’s check_cxx_source_compiles module:
include(CheckCXXSourceCompiles) check_cxx_source_compiles(" #include <memory> int main() { auto ptr = std::make_unique<int>(42); return 0; } " HAVE_MAKE_UNIQUE) if(NOT HAVE_MAKE_UNIQUE) message(FATAL_ERROR "Compiler does not support std::make_unique!") endif()
That said, this is overkill for most projects—sticking to the standard-based approaches above is simpler and more maintainable.
内容的提问来源于stack exchange,提问作者Gluttton

