__builtin_expect myassert()

来源:互联网 发布:c socket编程 编辑:程序博客网 时间:2024/06/06 04:14

 

 

这个assert功能比较齐全,原帖地址是

http://blog.csdn.net/sealyao/archive/2011/01/30/6169568.aspx

  1. //-------file main.c----------  
  2. #include <stdio.h>  
  3. #include "myassert.h"  
  4.   
  5. int func(const char *filename);  
  6.   
  7. int main(int argc,char **argv)  
  8. {  
  9.     MyAssert("two args are needed",argc==2);  
  10.     func(argv[1]);  
  11.     return 0;  
  12. }  
  13.   
  14.   
  15. //-------file func.c----------  
  16. #include <sys/types.h>  
  17. #include <sys/stat.h>  
  18. #include <fcntl.h>  
  19. #include <unistd.h>  
  20. #include "myassert.h"  
  21.   
  22. int func(const char *filename)  
  23. {  
  24.     int fd;  
  25.     MyAssert("filename can not be null",filename);  
  26.     MyAssert("file not exist",0==access(filename,F_OK));  
  27.     fd = open(filename,O_RDONLY);  
  28.     close(fd);  
  29.     return 0;  
  30. }  
  31.   
  32.   
  33. //-------file myassert.h----------  
  34. #ifndef __MY_ASSERT_H__  
  35. #define __MY_ASSERT_H__  
  36.   
  37. #include <stdio.h>  
  38. #include <stdlib.h>  
  39.   
  40. #define  MyAssert(message,assertion) do{/  
  41.     if(!(assertion)){/  
  42.         printf("line %d in %s(%s)", __LINE__, __FILE__,__FUNCTION__);/  
  43.         if(message){/  
  44.             printf(" : %s",message);/  
  45.         }/  
  46.         printf("/n");/  
  47.         abort();/  
  48.     }/  
  49. }while(0);  
  50. #endif  
  51.   
  52. #Makefile  
  53. TARGET = test  
  54. CC = gcc  
  55. CCFLAGS = -Wall  
  56. OBJS = main.o func.o  
  57.   
  58. $(TARGET) : $(OBJS)  
  59.     $(CC) -o $@ $(OBJS) $(CCFLAGS)  
  60.   
  61. %.o : %.c  
  62.     $(CC) -o $@ -c $< $(CCFLAGS)  
  63.   
  64. clean:  
  65.     rm -rf *.o   
  66.     rm -rf $(TARGET)

 

 

#include <stdio.h>
#include <stdlib.h>

#define likely(x)        __builtin_expect(!!(x), 1)
#define unlikely(x)        __builtin_expect(!!(x), 0)

#define BUG_ON(condition) do /
        { if (unlikely((condition)!=0)) /
                printf("BUG: failure at %s:%d/%s()!/n", __FILE__, __LINE__, __FUNCTION__); /
        } while(0)



int main(void)
{
        int i = 7;

        BUG_ON(i!=10);

        return 0;
}