build_assert.h 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #ifndef CCAN_BUILD_ASSERT_H
  2. #define CCAN_BUILD_ASSERT_H
  3. /**
  4. * BUILD_ASSERT - assert a build-time dependency.
  5. * @cond: the compile-time condition which must be true.
  6. *
  7. * Your compile will fail if the condition isn't true, or can't be evaluated
  8. * by the compiler. This can only be used within a function.
  9. *
  10. * Example:
  11. * #include <stddef.h>
  12. * ...
  13. * static char *foo_to_char(struct foo *foo)
  14. * {
  15. * // This code needs string to be at start of foo.
  16. * BUILD_ASSERT(offsetof(struct foo, string) == 0);
  17. * return (char *)foo;
  18. * }
  19. */
  20. #define BUILD_ASSERT(cond) \
  21. do { (void) sizeof(char [1 - 2*!(cond)]); } while(0)
  22. /**
  23. * BUILD_ASSERT_OR_ZERO - assert a build-time dependency, as an expression.
  24. * @cond: the compile-time condition which must be true.
  25. *
  26. * Your compile will fail if the condition isn't true, or can't be evaluated
  27. * by the compiler. This can be used in an expression: its value is "0".
  28. *
  29. * Example:
  30. * #define foo_to_char(foo) \
  31. * ((char *)(foo) \
  32. * + BUILD_ASSERT_OR_ZERO(offsetof(struct foo, string) == 0))
  33. */
  34. #define BUILD_ASSERT_OR_ZERO(cond) \
  35. (sizeof(char [1 - 2*!(cond)]) - 1)
  36. #endif /* CCAN_BUILD_ASSERT_H */