F53
F53

Reputation: 51

g++ ignoring specified C++ standard

I am running g++ with the compile flag -std=c++17

despite this, I am getting errors that typically mean that the compiler doesn't have access to C++17 additions

#include <iostream>
#include <algorithm>

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

I compile with

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

and get the error:

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);
               ^~~

Upvotes: 1

Views: 989

Answers (1)

paxdiablo
paxdiablo

Reputation: 882716

If the compiler wasn't capable of doing C++17, I suspect it would complain about the flag you gave it.

I often get that error when I've forgotten to include required headers, algorithm in your specific case.


Other than that, all I can suggest is to include the gcc version in your question and provide the smallest complete program that exhibits the problem, allowing us to more easily diagnose it.

The version is important since, as per gcc docs:

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.

Hence, if you're on an earlier version, you may find certain irregularities.


To assist you, this small sample of mine seems to work fine so I'd suggest trying to compile it as well:

#include <iostream>
#include <algorithm>

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

The following transcript shows how I did it on my machine:

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

Another possibility: even though you state quite clearly you're compiling with that flag, check it. The error I get when using C++14 is very similar:

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);
      |                    ^~~~~

Temporarily replace the offending line with:

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

and ensure you get 201703.

Upvotes: 1

Related Questions