code_junkie

Is requiring a certain order for #includes in c++ a sign of bad library/header design?

Nov 13th, 2011
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. // A.cpp
  2. #include "A.h"
  3. #include "boost/shared_ptr.hpp"
  4. #include <vector>
  5.  
  6. class A {
  7. // ...
  8. };
  9.  
  10. //a.h
  11. #ifndef _A_H_
  12. #define _A_H_
  13.  
  14. //... code ...
  15.  
  16. #endif
  17. // -----------------
  18. //b.h
  19. #ifndef _B_H_
  20. #define _B_H_
  21. #include a.h
  22.  
  23. //... code ...
  24.  
  25. #endif
  26. // -----------------
  27. //main.cpp Try 1
  28. #include "b.h" //<- okay! b includes a, then does b
  29. // -----------------
  30. //main.cpp Try 2
  31. #include "a.h" //<- includes a
  32. #include "b.h" //<- okay! b includes a, but skips redefining it, then does b
  33. // -----------------
  34. //main.cpp Try 3
  35. #include "b.h" //<- b includes a, then does b
  36. #include "a.h" //<- okay! a skips redefining itself!
  37. // -----------------
  38. //main.cpp Try 4
  39. #include "a.h" //<- fail! b is not included anywhere =(
  40.  
  41. // A.h
  42. #pragma once
  43. // or the #ifndef trick
  44. #include "B.h"
  45.  
  46. // A.cpp
  47. #include "A.h"
  48.  
  49. // A.h
  50. #pragma once
  51. // or the #ifndef trick
  52. //#include "B.h"
  53.  
  54. // A.cpp
  55. #include "B.h"
  56. #include "A.h"
  57.  
  58. class B; // forward declaration
  59.  
  60. class A
  61. {
  62. void doStuff(const B& b);
  63. };
  64.  
  65. #include <A.h>
  66. #include <B.h>
  67.  
  68. int main()
  69. {
  70. A a;
  71. B b;
  72. a.doStuff(b);
  73. }
Add Comment
Please, Sign In to add comment