I wrote a following piece of code and analysed through QA C but it shows a warning 'x' has external linkage and is being defined without any previous declaration. Kindly help me to understand this.
Code:
#include <stdio.h>
int x;
void main()
{
}
The tool is correctly warning you against using bad programming practice. I suspect this is because you have the static analyser set to check for MISRA-C compliance.
First of all MISRA-C does not allow "global" variables, MISRA-C:2012 rule 8.7:
Functions and objects should not be defined with external linkage if they are referenced in only on translation unit.
Meaning this variable would either have to be static
or extern
.
The former makes sense, the latter is almost always very bad programming practice (with a few exceptions like some const
variables).
Now, if you intended to have this variable extern
, then there's another rule, which is likely the cause of the error, MISRA-C:2012 rule 8.4:
A compatible declaration shall be visible when an object or function with external linkage is defined.
Meaning that for MISRA compliance, you would need to have the extern declaration extern int x
visible inside the same translation unit. MISRA recommends putting it in a header file.
Also please note that bad code like this is flagged obsolescent by the standard and might not work in future versions of C, see C11 6.11.2:
6.11.2 Linkages of identifiers
Declaring an identifier with internal linkage at file scope without the static storageclass specifier is an obsolescent feature.
Even if it wasn't flagged as obsolete practice by C, you should still always avoid global variables and extern
, since that is the road to spaghetti programming and spaghetti tight coupling. Consider a different program design entirely.
All it means is that x
could be accessible outside the translation unit containing the above code. So its value could be changed by other translation units.
So the compiler is warning you of a potential loss of program stability.
But the elephant in the room. Fix that non-portable void main()
prototype. Use int main()
. Pretty please, with sugar on top.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With