How to compile C++ with C++11 support in Mac Terminal

前端 未结 2 1829
执笔经年
执笔经年 2020-12-07 08:13

I wanted to compile C++11 source code within Mac Terminal but failed. I tried g++ -std=c++11, g++ -std=c++0x, g++ -std=gnu++11 and

相关标签:
2条回答
  • 2020-12-07 08:22

    XCode uses clang and clang++ when compiling, not g++ (assuming you haven't customized things). Instead, try:

    $ cat t.cpp
    #include <iostream>
    
    int main()
    {
        int* p = nullptr;
        std::cout << p << std::endl;
    }
    $ clang++ -std=c++11 -stdlib=libc++ t.cpp
    $ ./a.out 
    0x0
    

    Thanks to bames53's answer for pointing out that I had left out -stdlib=libc++.

    If you want to use some GNU extensions (and also use C++11), you can use -std=gnu++11 instead of -std=c++11, which will turn on C++11 mode and also keep GNU extensions enabled.

    0 讨论(0)
  • 2020-12-07 08:40

    As others have pointed out you should use clang++ rather than g++. Also, you should use the libc++ library instead of the default libstdc++; The included version of libstdc++ is quite old and therefore does not include C++11 library features.

    clang++ -std=c++11 -stdlib=libc++ -Weverything main.cpp
    

    If you haven't installed the command line tools for Xcode you can run the compiler and other tools without doing that by using the xcrun tool.

    xcrun clang++ -std=c++11 -stdlib=libc++ -Weverything main.cpp
    

    Also if there's a particular warning you want to disable you can pass additional flags to the compiler to do so. At the end of the warning messages it shows you the most specific flag that would enable the warning. To disable that warning you prepend no- to the warning name.

    For example you probably don't want the c++98 compatibility warnings. At the end of those warnings it shows the flag -Wc++98-compat and to disable them you pass -Wno-c++98-compat.

    0 讨论(0)
提交回复
热议问题