How to create a Singleton in C?

前端 未结 6 1190
感动是毒
感动是毒 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:35

    Just do

    void * getSingleTon() {
        static Class object = (Class *)malloc( sizeof( Class ) );
        return &object;
    }
    

    which works in a concurrent environment too.

提交回复
热议问题