如何在MacOS上使用C++98编译?

3

我需要在大学编程课程中使用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进行编译。

这里失败了(如预期)- 实时 - https://godbolt.org/z/r3od175Wh,你使用的是哪个版本的clang和g++? - Richard Critten
您可以使用此网站生成make文件 https://solver.assistedcoding.eu/makefilegen - Ayxan Haqverdili
@RichardCritten 我已经添加了clang和g++的版本。 - Charn
3个回答

2
尝试使用-std=c++98 -pedantic。这将严格执行特定的标准。

0

我找到了一个简单的解决方案:使用homebrew安装gcc,然后使用g++-11进行编译。


请添加更多细节以扩展您的答案,例如工作代码或文档引用。 - Community

0

免责声明:由于我没有Mac,这部分内容是猜测

据我了解,在Mac上clang++是默认编译器,因此即使使用g++,也很可能默认使用LLVM的libc++和头文件。而std::stoilibc++头文件中被无条件声明。

如果您使用g++libstdc++工具链,则可能会得到所需的错误:

clang++ -stdlib=libstdc++ -std=c++98 -o main main.cpp

我认为MacOS不再包括-stdlib=libstdc++(我已将错误添加到帖子中)。有没有手动安装的方法? - Charn
@Charn 我相信有这样的东西,但我没有使用过 MacOS 的经验。也许它可以在 homebrew 或者 MacOS 的包管理器中找到。最坏的情况是,你可以下载 gcc 并编译它。 - Ted Lyngmo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接