Mac下使用-std=c++17编译报错及头文件兼容问题求助
Hey there, let's work through your C++17 compilation issues with Apple Clang 9.0.0 step by step:
1. Fixing the -std=c++17 invalid value error
Your Apple LLVM version 9.0.0 (clang-900.0.39.2) predates the final official release of C17. At this stage, the draft C17 standard was still referenced using the -std=c++1z flag instead of the final -std=c++17 parameter.
To resolve the compile error, replace your flag with one of these options:
- Use
-std=c++1zfor strict compliance with the C++17 draft standard - Use
-std=gnu++1zif you need to enable GNU extensions alongside C++17 features
2. Why you need <experimental/optional> instead of <optional>
Clang 9.0.0 only offers partial support for C++17 standard library components. Many newer utilities like optional hadn't been moved from the experimental namespace to the standard namespace yet—they were still in the experimental staging area while the standard was being finalized.
You have two paths forward here:
- Keep using your current setup: Continue with
#include <experimental/optional>and access the type asstd::experimental::optional - Upgrade for full C++17 support: Update Xcode to version 10 or later (which ships with Clang 10+). This version fully supports the
-std=c++17flag, includes the standard<optional>header, and lets you usestd::optionaldirectly.
Quick verification test
To confirm the fix works, try compiling this sample program:
#include <experimental/optional> #include <iostream> int main() { std::experimental::optional<int> opt = 42; if (opt) { std::cout << *opt << std::endl; } return 0; }
Run this compile command:
clang++ -std=c++1z your_file.cpp -o test_program
内容的提问来源于stack exchange,提问作者Max0u

