Search code examples
c++macosc++11gnutoolchain

getting c++11 - compliant compiler


This all seems like a colossal mess.
All I want is a compiler that implements C++11, so I can use <chrono>. But I'm so confused from the very beginning.

Currently, I build programs by invoking G++, but when I check the version via $ g++ -v, I get:

gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)


What's going on? Am I using G++? GCC? LLVM? I don't even know. Are they the same thing?


So now I'm trying to build and download GCC 4.7 via gnu.org, but I have no idea what any of the guides are talking about. I've never seen so many acronyms for things I dont know.

Why is this so complicated? What's with all those versions, with some of them only implementing some parts of C++11 and not others?


Solution

  • Here's the situation on OS X.

    There are two C++ compilers installed by default.

    [5:49pm][wlynch@watermelon ~] g++ --version
    i686-apple-darwin11-llvm-g++-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)
    
    [5:49pm][wlynch@watermelon ~] clang++ --version
    Apple LLVM version 4.2 (clang-425.0.24) (based on LLVM 3.2svn)
    

    g++ is running llvm-gcc, which is the gcc frontend, and then the llvm backend.

    clang++ is running clang, which is the clang frontend and then the llvm backend.

    If you want a C++11 compiler on OS X without installing other packages, your only option is to use the clang compiler.

    The flags necessary are:

    clang++ -stdlib=libc++ -std=gnu++11
    

    To describe the two flags I'm passing:

    • -stdlib=libc++ uses the libc++ standard library, instead of the gnu libstdc++. On OS X, the libc++ version has c++11 support. The gnu libstdc++ one does not.
    • -std=gnu++11 tells the compiler to support c++11 code features, like lambdas and enum class. You can also pass -std=c++11, which is similar, but does not enable some commonly expected gnu extensions.

    Update for OS X 10.9: As of OS X Mavericks, both g++ and clang++ are actually using clang. The only difference, is that g++ will imply -stdlib=libstdc++ and clang++ will imply -stdlib=libc++. So, on Mavericks, if you'd like to use C++11, you can follow the above advice, or just do:

    clang++ -std=gnu++11
    

    Update for OS X 10.10: As of OS X Yosemite, g++ is still clang in disguise. However, neither uses libstdc++ by default anymore. Both are now on libc++.