Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QA C warning message in C Code [duplicate]

Tags:

c

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()
{
}
like image 554
Santz Avatar asked Jun 07 '16 07:06

Santz


2 Answers

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.

like image 199
Lundin Avatar answered Sep 22 '22 12:09

Lundin


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.

like image 35
Bathsheba Avatar answered Sep 18 '22 12:09

Bathsheba