1

Perhaps this is a dumb question and the answer is just "use a global", but I'm wondering how the concept of a singleton is usually done in C. For example, let's say I have a group of proxies that will never change during the execution of the program, but every function/thread/whatever needs access to it. I was thinking doing something like this:

typedef struct proxy {
    int fails;
    char http[50];
    char https[50];
} Proxy;

Proxy PROXIES[] = {
    {.fails=0, .http="http://...", .https="https://..."},
    {.fails=-1}; // use sentinel for sizeof?
};

Does the above seem like a valid way to do this? If not, what are some ways this is done in C?

carl.hiass
  • 1,526
  • 1
  • 6
  • 26
  • 1
    Does this answer your question? [How to create a Singleton in C?](https://stackoverflow.com/questions/803673/how-to-create-a-singleton-in-c) – i9or Mar 16 '21 at 20:10
  • Declare your code somewhere at the top of a `h` file that gets included everywhere and you will get a singleton. Plus you will get a compiler support for it, like name clashes. – user14063792468 Mar 16 '21 at 20:34

1 Answers1

1

Your solution is perfectly fine for simple objects. However for more complex ones you may require some initialization:

Header:

typedef struct proxy { ... } Proxy;
const Proxy *get_proxy(void);

C file:

const Proxy *get_proxy(void) {
  static int initialized = 0;
  static Proxy proxy;
  if (!initialized) {
    // ... do initialization
    initialized = 1;
  }
  return &proxy;
}
tstanisl
  • 13,520
  • 2
  • 25
  • 40
  • 1
    Your code as currently posted is not thread-safe. If multiple threads call `get_proxy()` simultaneously you will introduce race conditions into the system. – Andrew Henle Mar 16 '21 at 21:55
  • 1
    @tstanisl -- small thing, but why do you do `*get_proxy()` instead of `*get_proxy(void)` -- isn't the second method more correct? – carl.hiass Mar 16 '21 at 22:51
  • 1
    @carl.hiass, laziness... You are perfectly right. Thanks for pointing that – tstanisl Mar 16 '21 at 22:58