3

I had an enum TokenType defined in one of the header files in my project.

When I later included <windows.h> to some header, the compiler complained it already defines its own TokenType.

What is the convention in C to avoid such naming collisions? Must I name any public thing used throughout my project (function, enum, typedef struct, etc.) with a MyProject_ prefix? For example MyProject_TokenType? It seems ugly. What is the common approach to this?

What would be the common approach for libraries, and what would be the approach for standalone applications (such as my own)?

Aviv Cohn
  • 15,543
  • 25
  • 68
  • 131
  • Just `myTokenType`? Or change the name to reflect its use/function. – Paul Ogilvie May 17 '19 at 14:24
  • 2
    In C you don't have namespaces, so it's common practice in professional projects to add a project prefix or (in big projects) a module prefix to all global identifiers. – Bodo May 17 '19 at 14:31
  • There may be kludges possible, such as creating a separate source file that includes the library headers and re-exports them using your own names, but these may be inadequate (e.g., your other sources may need type definitions that are not easily reproduced with your own names). The basic problem here is that a third-party library may be poorly designed, and there may be no good fix for that. Writing a general answer to cover numerous possibilities may be too broad. Addressing specific problems may be a more reasonable goal. – Eric Postpischil May 17 '19 at 14:34
  • IMO if your project is not a library, you don't need to use prefixes – just rename your things in case there are conflicts when you add libraries. (Of course the feasibility of renaming stuff depends on the size of the project and number of collaborators.) If your project _is_ a library (or has library-like parts), then you will want to avoid conflicts with other libraries, and using a prefix is the most common way to accomplish that. Also try to minimize the number of globals (e.g., use file `static` scope where possible). – Arkku May 17 '19 at 14:36
  • I big projects public (`extern`) functions, types and variables has prefix be name of file ex. `extern void myLib_nameOfMyFunction(void);`. Not applicable for private (`static`) functions, variables, types. – Igor Galczak May 17 '19 at 14:37

1 Answers1

3

Since ANSI C does not have namespace support, prepending the project/file name to the global variable/type is the most practical option I encountered to date. Although it makes the name longer, I also find it more organized and readable, in addition of the advantage of collision avoidance.

Bora
  • 451
  • 2
  • 5