How to run C++17 on Mac M1/M2/M3
Ayush Pattnaik
Posted on June 6, 2021
Having problems using STL
functions_ of C++14
or C++17
?
Wrote a piece of code in C++
and encountered that STL
functions are not supported by the default clang compiler on Mac?
For example, this piece of code:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n=gcd(2,3);
cout<<n;
return 0;
}
Compiling the code with gnu
or clang
compilers and getting this error?
@User-MacBook-Air % clang++ test.cpp
test.cpp:5:11: error: use of undeclared identifier 'gcd'
int n=gcd(2,3);
^
1 error generated.
So what happened here?
Let's check our c++
version.
When you run clang --version
, you will get something like this and would be pretty confused even if your clang/gnu
is up-to-date but you still can't figure out your c++
version:
Apple clang version 12.0.5 (clang-1205.0.22.9)
Target: arm64-apple-darwin20.4.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
This happens because
The gcd() function is a STL function from c++14 and above.
But by default, Clang builds
C++
code according to theC++98
standard, with manyC++11
features accepted as extensions.
What to do?
After going through many websites and resources, I was finally able to compile the correct methods to use c++17 on mac.
So in order to use STL functions of c++17
or c++14
or upper versions, you need to specify the version of C++ to be used which goes like this:
-std=c++{version} {filename}.cpp
appending the c++ version to -std option.
Example:
-
For
clang
compilers:
clang++ --std=c++17 {filename}.cpp
-
For
gnu
compilers:
g++ --std=gnu++17 {filename}.cpp
-
My Personal choice:
c++ --std=gnu++17 {filename}.cpp
And that's it, you're done!
Also free feel to share other ways in the comments!!!
Posted on June 6, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.