C – Why extern declarations should be outside the .c file (according to the Linux coding style)

Why extern declarations should be outside the .c file (according to the Linux coding style)… here is a solution to the problem.

Why extern declarations should be outside the .c file (according to the Linux coding style)

According to the checkpatch.pl script “External declaration outside of .c file”
(Used to check if the patch follows the coding style)
Note: This works fine without compile warnings
This problem was solved by putting the extern declaration in the .h file.

a.c
-----
int x;
...

b.c 
----
extern int x;

==>Checkpatch prompt

a.h
-----
extern int x;

a.c
----
int x;

b.c
---- 
#include "a.h"

==> No prompt

I want to see why this is better

My guess.
Ideally, the code is split into files to modularize the code (each file is a module)
The interfaces exported by the module are placed in header files so that other modules (or .c files) can contain them. So if any module wants to expose some variables to the outside world, then you must add an extern declaration to the header file corresponding to the module.

Again, each module (.c file) has a corresponding header file that appears to be
There are a lot of header files.

Solution

It would be better to include a.h in the a.c file as well. This allows the compiler to verify that declarations and definitions match each other.

a.h
-----
extern int x;

a.c
----
#include "a.h"  <<--- add this
int x;

b.c
---- 
#include "a.h"

As you can imagine, the reason for this rule is that we should use a compiler to check what we are doing. Tiny details are much better.

If we allow extern declarations everywhere, then we will be in trouble if we want to change x to something else. How many .c files do we have to scan to find all extern int x? A lot. If we do, we may also find some extern char x errors. Oops!

Just declare one in the header file and include it where you need it to save you a lot of trouble. In any real project, x won’t be the only element in the header file anyway, so you won’t save on file count.

Related Problems and Solutions