如何在 Mac 终端中使用 C++11 支持编译 C++

2021-12-28 00:00:00 macos terminal g++ c++ c++11

我想在 Mac 终端中编译 C++11 源代码但失败了.我尝试了 g++ -std=c++11g++ -std=c++0xg++ -std=gnu++11g++ -std=gnu++0x 但没有任何效果.终端总是读取无法识别的命令行选项.但是,g++ -std=gnu 之类的东西运行良好(当然 C++11 源代码无法通过).

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 g++ -std=gnu++0x but nothing worked. Terminal always read unrecognized command line option. However, g++ -std=gnu and things like that worked fine (of course C++11 source code could not pass).

我应该使用哪个选项来开启 C++11 支持?

Which option should I use to turn on C++11 support?

顺便说一下,我使用的命令行工具安装在 Xcode 中,我很确定它们是最新的.

By the way, the command line tool I'm using is installed within Xcode, and I'm pretty sure that they are up-to-date.

推荐答案

正如其他人所指出的,您应该使用 clang++ 而不是 g++.此外,您应该使用 libc++ 库而不是默认的 libstdc++;包含的 libstdc++ 版本很旧,因此不包含 C++11 库功能.

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

如果您还没有为 Xcode 安装命令行工具,您可以使用 xcrun 工具运行编译器和其他工具,而无需这样做.

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

此外,如果您想禁用某个特定警告,您可以将其他标志传递给编译器来执行此操作.在警告消息的末尾,它会向您显示将启用警告的最具体的标志.要禁用该警告,请在警告名称前加上 no-.

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.

例如,您可能不想要 c++98 兼容性警告.在这些警告结束时,它会显示标志 -Wc++98-compat 并禁用它们,您可以通过 -Wno-c++98-compat.

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.

相关文章