首页 > 解决方案 > Missing declaration for object definition (Rule MisraC2012-8.4)

问题描述

I try to understand what to do with this error:
required: Missing declaration for object definition [hi] (Rule MisraC2012-8.4)
My code is:

typedef struct {
    int l;
} some_struct;

some_struct hi = {
    5
};

int main(void) {
    return(0);
}


static solve this issue but I need to use this variable as extern from another file.

标签: cmisra

解决方案


Rule 8.4 is regarding type incompatibility of objects with external linkage. There's a possible severe bug that the rule aims to prevent from: declaring the object as one type in one file, then define it as another type in another file.

To prevent such bugs, MISRA therefore requires that a previous extern declaration of the object is visible to the file that contains the definition.

So if you aim to have some_struct hi defined at file scope, you must add a declaration somewhere too, preferably in a header file:

extern some_struct hi;

static solves the problem because then you no longer have external linkage and the rule does not apply then.

Please note that (non-const) extern spaghetti globals are highly discouraged in any form of program, MISRA or no MISRA. In the vast majority of possible cases, the presence of such global variables in a program is caused by bad program design.


推荐阅读