23

In some C projects, function names start with a common prefix indicative of the module name, for example:

mymodule_do_this_stuff();

mymodule_do_that_stuff();

Is there a justification for doing so when the linkage is internal, and there is no possibility of namespace collisions?

For example,

static void mymodule_do_this_stuff(void)
{
  ...
}
ilkkachu
  • 151
user6007354
  • 341
  • 2
  • 5

3 Answers3

40

Why prefixes in the first place?

The prefix for function names is a C practice that intends to avoid naming conflicts.

This is especially suitable in big projects, where different teams could easily come with do_this() and do_that() in different subcomponents of a large codebase.

Since C lacks of a namespace or a package feature, the prefix is the most common workaround. It’s not the only workaround: There are other approaches , but with their own drawbacks.

Does it make sense for static functions?

Of course, prefixing internal static functions does not reduce any naming conflict. This is a side effect of the prefix scheme decided in the first place.

The reasons that justifies this practice are:

  • consistency in the naming scheme: if 80% of the time you use a prefix, not having it on the 20% remaining functions might cause more confusion than you’d expect.
  • flexibility in the evolution: bear in mind that all static functions were not necessarily static from their inception. static or not static is something that could change over time. And mixing prefixed and unprefixed name could make such natural changes more painful than necessary.
Christophe
  • 81,699
17

There are two important types of naming collisions here. You are correct in that the compiler won't have any trouble differentiating between the functions due to scope rules. Your problem is that you still have collisions inside the programmer's brain.

Think about it this way: if you have 8 modules that all have a process_data() function, and you get a stacktrace that shows a fault inside process_data(), which module generated the fault? Having the module name as a prefix makes it much easier to glance at the names and immediately know which process_data is being referred to without having to do a lot of detective work.

bta
  • 1,199
16

There is another reason to use prefixed names even for file-local functions: they can be navigated with simple text search and text indexers without full analysis of language scoping, such as id-utils. Given that C projects often have their history going back to 90x and even earlier, it is an important reason.

max630
  • 2,605