How to create a Singleton in C?

前端 未结 6 1209
感动是毒
感动是毒 2020-12-08 01:11

What\'s the best way to create a singleton in C? A concurrent solution would be nice.

I am aware that C isn\'t the first language you would use for a singleton.

6条回答
  •  广开言路
    2020-12-08 01:24

    Here's another perspective: every file in a C program is effectively a singleton class that is auto instantiated at runtime and cannot be subclassed.

    • Global static variables are your private class members.
    • Global non static are public (just declare them using extern in some header file).
    • Static functions are private methods
    • Non-static functions are the public ones.

    Give everything a proper prefix and now you can use my_singleton_method() in lieu of my_singleton.method().

    If your singleton is complex you can write a generate_singleton() method to initialize it before use, but then you need to make sure all the other public methods check if it was called and error out if not.

提交回复
热议问题