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!!!
Top comments (4)
is there any method through which we don't have to write this command again and again
and btw thanku so much it worked for me
ok i got it answer of my question use code runner extention in vs code and go to its json file and find cpp and change that line to
"cpp": "cd $dir && c++ --std=gnu++17 $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt"
this
I got this error on my Mac:
Hi, checkout this solution. It worked for me
stackoverflow.com/a/40935471/13556971
Since, bits/stdc++ is a GNU GCC extension, whereas OSX uses the clang compiler.
You have to create bits directory inside /usr/local/include and then make a header file stdc++.h inside bits and paste the contents of this gist(gist.github.com/sachin-kmr/ee03a0d...) inside it. Then, it should compile as expected.
Since, /usr directory is hidden by default on Mac OSX.
Nice!