Reputation: 2426
In our codebase, I often come across functions defined in the .cpp as
void foo() { ... }
by they do not appear in the corresponding header.
These are implicitly extern
.
For most of these cases, it is a smell that the function should have been defined as static
.
I would like to collect these cases and review them.
The intention is to clear all accidental external linkages.
Q: Is there a practical way to identify such definitions? or is there some tool?
I was thinking of using nm
to find external symbols, and then search for them in the corresponding headers.
If they are not found, then they should have internal linkage.
But I don't know how to tell if a symbol is a free function or not.
Upvotes: 0
Views: 107
Reputation: 215090
MISRA C and MISRA C++ have rules stating that functions/variables declared at file scope and only used in one translation unit should be declared as static
to ensure internal linkage. Or in case of file scope variables only used by one function, declare them at local scope instead. See for example MISRA C:2012 rules 8.7, 8.8 and 8.9. These are very sound rules that apply to all C and C++ programs, not just those written for critical systems.
So you could run a MISRA checking static analyser and it will point out which functions and variables that need changing. Any half-decent static analyser will have MISRA support.
Though please note that tool recommendation questions are explicitly off-topic here, so kindly don't ask which tool to pick. Such questions may be on-topic at https://softwarerecs.stackexchange.com
Upvotes: 3