fork(1) download
  1. // singleton.h
  2.  
  3. typedef int (*GetterFunc)(void);
  4. typedef void (*SetterFunc)(int);
  5.  
  6. typedef struct
  7. {
  8. GetterFunc GetFoo;
  9. GetterFunc GetBar;
  10. SetterFunc SetFoo;
  11. SetterFunc SetBar;
  12. } Singleton;
  13.  
  14. Singleton* GetSingleton();
  15.  
  16. // singleton.c
  17.  
  18. #include <stdbool.h>
  19.  
  20. static int foo;
  21. static int bar;
  22.  
  23. static int GetFooImpl()
  24. {
  25. return foo;
  26. }
  27.  
  28. static int GetBarImpl()
  29. {
  30. return bar;
  31. }
  32.  
  33. static void SetFooImpl(int value)
  34. {
  35. foo = value;
  36. }
  37.  
  38. static void SetBarImpl(int value)
  39. {
  40. bar = value;
  41. }
  42.  
  43. Singleton* GetSingleton()
  44. {
  45. static bool isInitialized;
  46. static Singleton instance;
  47.  
  48. if (!isInitialized)
  49. {
  50. instance.GetFoo = &GetFooImpl;
  51. instance.GetBar = &GetBarImpl;
  52. instance.SetFoo = &SetFooImpl;
  53. instance.SetBar = &SetBarImpl;
  54. isInitialized = true;
  55. }
  56.  
  57. return &instance;
  58. }
  59.  
  60. // test.c
  61.  
  62. #include <stdio.h>
  63.  
  64. int main(void)
  65. {
  66. int myFoo, myBar;
  67.  
  68. Singleton* instance = GetSingleton();
  69. instance->SetFoo(1);
  70. instance->SetBar(2);
  71.  
  72. myFoo = instance->GetFoo();
  73. myBar = instance->GetBar();
  74.  
  75. printf("foo=%d, bar=%d", myFoo, myBar);
  76. }
  77.  
Success #stdin #stdout 0s 5532KB
stdin
Standard input is empty
stdout
foo=1, bar=2