如果在user.hpp中定义了boost_NO_EXCEPTIONS,则无法编译boost::shared_ptr的原因

why boost::shared_ptr can not be compiled if BOOST_NO_EXCEPTIONS is defined in user.hpp

本文关键字:boost 编译 shared ptr EXCEPTIONS hpp user 定义 如果 NO      更新时间:2023-10-16

我有一个嵌入式系统,想在这个系统中使用boost,但需要禁用异常,因为我不想支付异常的费用。

Boost提供了一个user.hpp和可设置的宏选项Boost_NO_EXCEPTIONBoost_NO_EXCEPTION_STD_NAMESPACE,但如果定义了这两个宏,则无法编译Boost::shared_ptr(更确切地说,无法链接)。

shared_ptr_boost.cpp:(.text._ZN5boost6detail12shared_countC2IiEEPT_[_ZN5boost6detail12shared_countC5IiEEPT_]+0x7a): undefined reference to `boost::throw_exception(std::exception const&)'
collect2: error: ld returned 1 exit status

为什么boost提供宏选项,但不承诺使用这些选项进行编译?

它可以编译。

它就是无法链接。

这是因为,如果定义BOOST_NO_EXCEPTIONS,则必须在某个地方提供boost::throw_exception(std::exception const&)的实现,以取代通常的错误引发功能。

阅读throw_exception.hpp:中的评论

namespace boost
{
#ifdef BOOST_NO_EXCEPTIONS
void throw_exception(std::exception const & e); // user defined
#else
//[Not user defined --Dynguss]
template<class E> inline void throw_exception(E const & e)  
{
    throw e;
}
#endif
} // namespace boost

这是我的最终解决方案。

shared_ptr_boost.cpp:

#include <boost/shared_ptr.hpp>
#include <stdio.h>
#include <exception>
namespace boost{
  void throw_exception(std::exception const &e){}
}
int main(){
  boost::shared_ptr<int> pName(new int(2));
  *pName += 3;
  printf("name = %dn", *pName);
  return 0;
}

编译命令:

arm-hisiv100-linux-uclibcgnueabi-g++ -I../boost_1_59_0/ -DBOOST_NO_EXCEPTIONS -DBOOST_NO_EXCEPTION_STD_NAMESPACE -fno-exceptions shared_ptr_boost.cpp

对于这样一个小的测试程序,我得到了大约1.7K的可执行文件;这就是我不想为例外而付出的代价。