csingletonunnamed-class

What are the problems with creating a Singleton using an unnamed struct in C?


I want to create a singleton struct in C and came up with this idea of using an unnamed struct for defining a global variable that we can't create another instance of it because it's struct is unnamed (therefore we have a singleton).

#ifndef __for_including_this_file_once__
#define __for_including_this_file_once__

struct { variables } singleton_strcut;

#endif // __for_including_this_file_once__

This way we can access this instance only by its name anywhere we include this .h file.


Solution

  • This won't work if you have multiple .c files. If more than one source file includes this header, you'll end up with a multiple definition error when you reach the linker phase.

    You would need to put a declaration in the header file and a definition in exactly one source file, and to do that you would need to give the struct a name.