查看: 132|回复: 1

彻底去除C++异常运行时

[复制链接]

8

主题

16

帖子

35

积分

新手上路

Rank: 1

积分
35
发表于 2022-9-23 07:32:51 | 显示全部楼层 |阅读模式
去除C++异常运行时,换句话说,就是整个C++程序不依赖异常,但是std、boost等等都使用到异常,那怎么办呢?
对于std,构建GCC时,添加选项--enable-cxx-flags='-fno-exceptions',这样标准库就不会抛异常,会直接调用std::abort,Exceptions (gnu.org),反正标准库的异常我也没见过有人catch,你也没法处理,特别是bad_alloc,在64位系统上能不能得到这个异常都是个问题。
对于boost,我们在使用b2构建boost时,传递cxxflags,例如./b2 install cxxflags="-fno-exceptions",boost库很多函数都提供了error_code重载。最后还要在自己项目里提供以下函数,想怎么写就怎么写。
namespace boost
{
        void throw_exception(std::exception const& e)
        {
                std::puts(e.what());
                std::abort();
        }
        void throw_exception(std::exception const& e, boost::source_location const&)
        {
                std::puts(e.what());
                std::abort();
        }
}
automake和cmake的项目也是同理,传递CXXFLAGS即可。
回复

使用道具 举报

4

主题

14

帖子

27

积分

新手上路

Rank: 1

积分
27
发表于 2025-3-4 19:57:33 | 显示全部楼层
元芳你怎么看?
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表