【问题标题】:No warning or error indication when variable defined as static but declared as extern变量定义为静态但声明为外部时没有警告或错误指示
【发布时间】:2012-01-26 01:12:49
【问题描述】:

我今天遇到了一些令我惊讶的代码。 .c 文件中的变量(在函数之外)被定义为静态的。但是,在 .h 文件中,它被声明为 extern。下面是一个类似的代码示例:

.h 中的结构定义和声明:

typedef struct
{
    unsigned char counter;
    unsigned char some_num;
} One_Struct;

typedef struct
{
    unsigned char counter;
    unsigned char some_num;
    const unsigned char * p_something;
} Another_Struct;

typedef struct
{
    One_Struct * const p_one_struct;
    Another_Struct * const p_another_struct;
} One_Useful_Struct;

extern One_Useful_Struct * const p_my_useful_struct[];

.c 中的定义和初始化:

static One_Useful_Struct * const p_my_useful_struct[MAX_USEFUL_STRUCTS] =
{
    &p_my_useful_struct_regarding_x,
    &p_my_useful_struct_regarding_y,
};

问题: 所以我的问题是,为什么我没有收到编译器错误或警告?

代码已经在其他项目中成功运行一段时间了。我确实注意到该指针从未在定义它的 .c 文件之外使用,并且被正确定义为静态(我删除了外部声明)。我发现它的唯一原因是因为我在项目上运行了 Lint,然后 Lint 将其拾取。

【问题讨论】:

    标签: c


    【解决方案1】:

    这肯定不是标准的 C。GCC 和 clang 都检测到这种情况并给出错误:

    $ gcc example.c
    example.c:4: error: static declaration of ‘x’ follows non-static declaration
    example.c:3: error: previous declaration of ‘x’ was here
    $ clang example.c
    example.c:4:12: error: static declaration of 'x' follows non-static declaration
    static int x;
               ^
    example.c:3:12: note: previous definition is here
    extern int x;
               ^
    1 error generated.
    

    您必须使用相当宽松的编译器 - 也许是 Visual Studio?我刚刚检查了我的 Windows 机器,VS2003 默默地接受了我的示例程序。添加/Wall 确实会发出警告:

    > cl /nologo /Wall example.c
    example.c
    example.c(4) : warning C4211: nonstandard extension used : redefined extern to static
    

    在我看来,您正在使用您正在使用的任何编译器的扩展。

    【讨论】:

    • 这是一个很好的观点,我将不得不研究哪些扩展已经到位。我正在为 ARM 使用 Keil uVision。
    • 没有任何奇怪的扩展。它必须只是这个编译器的东西。感谢您的意见,我很感激。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多