Check for C++ global functions declared separate from definition

I like having a connection between function declaration and the function definition that forces the signatures to match. When you declare a function in a class or in a namespace, you need to either define the function inline or the function definition needs to be qualified with the class or namespace that the function belongs to. That means that if you change the function signature in one of those places, you get a compilation error. Meanwhile, if you declare a function in the global scope and define it later, you have no such connection, and if you change the signature in one of these locations in that case, you get a linker errors. I think linker errors are typically a lot harder to resolve than compilation errors, because they often don’t point you directly at the line that causes the error.

Because you have the option to reopen a namespace, unlike a class, it is possible to declare a function inside a namespace, and then later have the function definition inside a reopened namespace. This has the same issue of having the function definition act also as a function declaration.

Examples:

  • Global scope declaration separate from defintion should be non-compliant
void someFunc(int someArg);

void someFunc(int someArg) // Non-compliant - already declared
{
}
  • Function defined inline is compliant
// Compliant
void someFunc(int someArg)
{
}
  • Function defined inline in a namespace is compliant
// Compliant
namespace ns
{
void someFunc(int someArg)
{
}
} // namespace ns
  • Reopening namespace to define the previously defined function should be non-compliant
namespace ns
{
void someFunc(int someArg);
} // namespace ns
namespace ns
{
void someFunc(int someArg) // Non-compliant - already declared
{
}
} // namespace ns
  • Namespace function defined separately with qualifier is compliant
// Compliant
namespace ns
{
void someFunc(int someArg);
} // namespace ns

void ns::someFunc(int someArg)
{
}

For the purposes of this rule, the anonymous namespace behaves like the global scope, but you can declare named namespaces nested inside the anonymous namespace in the event that defining functions inline isn’t an option.

Class member functions are syntactically required to adhere to this rule.

Hello @torgeir.skogen,

I think it makes sense, so I created a ticket for it: [CPP-3863] - Jira.

Thanks for sharing your idea.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.