You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过CMake target_compile_feature确保支持std::make_unique?

Fixing 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_14 with target_compile_features
    This tells CMake to enable C++14 (or higher) support for your target, which includes std::make_unique by default:

    target_compile_features(target_name PRIVATE cxx_std_14)
    

    The PRIVATE keyword ensures this setting only applies to your target’s own compilation (adjust to PUBLIC or INTERFACE if 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, use set_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 22:17:51