我需要在大学编程课程中使用C++98,但是即使在clang++或g++中传递-std=c++98标志,它似乎仍会使用c++11进行编译,并且如果我使用c++11功能,则不会出现错误。以下是一个简单的示例:
#include <string>
#include <sstream>
using namespace std;
int main()
{
int i;
string number = "12";
i = stoi(number);
}
我的 makefile:
all:
clang++ -std=c++98 -c *.cpp
clang++ -o main *.o
clean:
rm -f *.o main
run: clean all
./main
然后我在终端中运行make命令(我尝试使用clang++代替g++,但结果相同),并收到以下输出:
➜ cppversion make
g++ -std=c++98 -c *.cpp
g++ -o main *.o
➜ cppversion make
clang++ -std=c++98 -c *.cpp
clang++ -o main *.o
➜ cppversion
我认为如果 -std=c++98 标志起作用,这段代码不应该编译。我该如何强制使用 c++98 编译这段代码?
这是 clang 的版本:
Apple clang version 12.0.5 (clang-1205.0.22.11)
Target: x86_64-apple-darwin20.2.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin\
这里是g++的版本:
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX11.1.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.5 (clang-1205.0.22.11)
Target: x86_64-apple-darwin20.2.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
我还尝试使用-pedantic标志,但它无法解决问题。
使用-stdlib=libc++标志会产生以下结果:
➜ cppversion make
clang++ -stdlib=libstdc++ -std=c++98 -c *.cpp
clang: warning: include path for libstdc++ headers not found; pass '-stdlib=libc++' on the command line to use the libc++ standard library instead [-Wstdlibcxx-not-found]
main.cpp:1:10: fatal error: 'string' file not found
#include <string>
^~~~~~~~
1 error generated.
make: *** [all] Error 1
如果只将其更改为-stdlib=libc++,则仍然可以编译:
➜ cppversion make
clang++ -stdlib=libc++ -std=c++98 -c *.cpp
clang++ -o main *.o
➜ cppversion
我发现了一个简单的解决方案:使用Homebrew安装gcc,并使用g++-11进行编译。