g++ 忽略指定的 C++ 标准

g++ ignoring specified C++ standard

我是 运行 g++,编译标志 -std=c++17

尽管如此,我收到的错误通常意味着编译器无法访问 C++17 附加功能

#include <iostream>
#include <algorithm>

int main() {
    int lo = 1;
    int hi = 99;
    int val = std::clamp(-3, lo, hi);
    std::cout << val << '\n';
}

我用

编译
g++ -std=c++17 -c -o test.o test.cpp

并得到错误:

test.cpp: In function 'int main()':
test.cpp:7:15: error: 'clamp' is not a member of 'std'
     int val = std::clamp(-3, lo, hi);
               ^~~

如果编译器不能执行 C++17,我怀疑它会抱怨你给它的标志

当我忘记在您的特定情况下包含必需的 headers、algorithm 时,我经常会遇到该错误。


除此之外,我只能建议在您的问题中包含 gcc 版本,并提供最小的完整程序来展示问题,让我们更容易诊断它。

版本很重要,因为根据 gcc 文档:

GCC 9.1 was the first release with non-experimental C++17 support, so the API and ABI of features added in C++17 is only stable since that release.

因此,如果您使用的是早期版本,您可能会发现某些不规范之处。


为了帮助您,我的这个小样本似乎工作正常,所以我建议您也尝试编译它:

#include <iostream>
#include <algorithm>

int main() {
    int lo = 1;
    int hi = 99;
    int val = std::clamp(-3, lo, hi);
    std::cout << val << '\n';
}

以下记录显示了我是如何在我的机器上完成的:

pax:~> g++ --version
g++ (Ubuntu 9.3.0-10ubuntu2) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

pax:~> g++ --std=c++17 -Wall -Wextra -Wpedantic -o prog prog.cpp

pax:~> ./prog
1

另一种可能性:即使您很清楚地声明您正在使用该标志进行编译,请检查它。我在使用 C++14 时得到的错误非常相似:

prog.cpp: In function ‘int main()’:
prog.cpp:7:20: error: ‘clamp’ is not a member of ‘std’
    7 |     int val = std::clamp(-3, lo, hi);
      |                    ^~~~~

暂时将违规行替换为:

 std::cout << __cplusplus << '\n';

并确保您获得 201703.