修改TestAssert.h (cppunit)——为什么包含的顺序对宏展开很重要

Modifying TestAssert.h (cppunit) - why the order of includes matter for macro expansion?

本文关键字:顺序 包含 TestAssert cppunit 修改 为什么      更新时间:2023-10-16

我有一个项目,它有两个基异常类;两者都有相同的名称,只是方法/成员不同(一个有返回消息的方法,另一个只有一个可以访问异常信息的字符串成员)。

我使用CPPUNIT进行测试,在框架中有TestAssert.hpp文件,其中包含每个断言的宏(CPPUNIT_ASSERT_NO_THROW等)。我已经修改了,在其中添加了另一个宏来测试测试类中包含的异常头,所以我可以捕获我的基本异常;宏看起来像这样:

#ifdef BASE_EXCEPTION_CLASS_ONE_HPP
#define MY_CPPUNIT
catch (BaseException &ex) {
ex.getMessage();
}
#endif
#ifdef BASE_EXCEPTION_CLASS_TWO_HPP
#define MY_CPPUNIT
catch (BaseException &ex) {
cout << "Caught: " ex.comment <<endl;
}
#endif

这两个宏将在TestAssert.h

中这样使用
/** Asserts that the given expression does not throw any exceptions.
 * ingroup Assertions
 * Example of usage:
 * code
 *   std::vector<int> v;
 *   v.push_back( 10 );
 *  CPPUNIT_ASSERT_NO_THROW( v.at( 0 ) );
 * endcode
 */
# define CPPUNIT_ASSERT_NO_THROW( expression )                             
   try {                                                                   
      expression;                                                          
   } catch ( const std::exception &e ) {                                   
      CPPUNIT_NS::Message message( "Unexpected exception caught" );        
      message.addDetail( "Type: " +                                        
                   CPPUNIT_EXTRACT_EXCEPTION_TYPE_( e,                     
                                       "std::exception or derived" ) );    
      message.addDetail( std::string("What: ") + e.what() );               
      CPPUNIT_NS::Asserter::fail( message,                                 
                                  CPPUNIT_SOURCELINE() ); }                
    MY_CPPUNIT                                                             
    catch ( ... ) {                                                        
      CPPUNIT_NS::Asserter::fail( "Unexpected exception caught",           
                                  CPPUNIT_SOURCELINE() );                  
   }

可以,但前提是在测试类中第一个#include是#include "test.hpp"

那么,宏扩展是如何受到包含顺序的影响的,或者我如何才能看到预处理部分,以便我能够以某种方式计算出来?

非常感谢!

您可以使用gcc -E查看预处理器后的输出。它包括所有展开的宏,并允许您查看宏展开时发生的情况。您还可以在第二步中编译该文件,如果问题最初在其中一个宏中,则可以获得更好的错误报告。