C语言static的小问题

查看:158
本文介绍了C语言static的小问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

为什么这个代码可以在vs2017中编译通过,而在GNU里面却不行呢?
书上说:static定义的静态变量的作用域是从定义之处开始,到文件结尾处结束,在定义之处前面的那些
代码行也不能使用它。想要使用就得在前面再加 extern。

但是我按照他说的实验了却存在问题,报错上说声明的不是静态变量,但是定义的时候是静态变量,但是vs却不报错,求大佬指点

#include <stdio.h>



extern int i;
void a()
{

    i = 10;
    printf( "%d", i );
}

int main()
{

    int j = i;
    a();
    i = 5;
    a();    
    return 0;
}
static int i;  //如果去掉static,这个程序可以编译通过

编译的信息如下:

static.c:22:12: error: static declaration of ‘i’ follows non-static declaration
 static int i;  //如果去掉static,这个程序可以编译通过
        ^
static.c:5:12: note: previous declaration of ‘i’ was here
 extern int i;

解决方案

Before explaining this problem,let's see an example given in the C++ Standard Section 7.1.1.8.

//first example
static int a;        //a has internal linkage
extern int a;      //a still has internal linkage
//second example
extern int b;        //b has external linkage
static int b;        //error:inconsistant linkage

First Example

static int a is a definition,which indicates that a has internal linkage.When extern occurs,the compilers has already known that a exists and accepts that it has internal linkage and carries on.

Second Example

The extern is a declaration,it implicitly states that b has external linkage,but it doesn't create anything.Since there's no definition before a declaration,the compiler registers b having external linkage.But when it gets to static statement, it finds the incompatible statement that it has internal linkage and gives an error.

Summary

In other words,this is because declarations are softer than definitions. e.g, you can declare the same thing multiple times without errors,but you can only define it once.

Reference on Stack Overflow

UPDATE:

If you do click this link,you would find someone had talked about the same problem.And I took a screenshot of it.Hope this can solve your haze:

Here is translation:
在Microsoft Visual Studio中,两个版本都编译的很好。但是GNU C ++上,就会出现错误。

我不知道哪个编译器是正确的。无论哪种方式,两条写法都没有多大意义。

extern int意味着i在一些其他模块(对象文件或库)中定义。这是一个声明。编译器不会将存储空间分配给该对象,但是当您在程序中的其他地方使用该变量时,它将会识别该变量。

int告诉编译器为i分配存储。这是一个定义。如果其他C++(或C)文件具有int i,链接器将报错,该int被定义两次。

static int和上说情况类似,其功能是使其成为该文件内有效,而不能从其他模块访问,即使他们被声明为extern int i。人们正在使用关键字static(在这种情况下)来保持变量本地化。

因此,当声明为在其他地方被定义,并且在模块中定义为静态似乎是一个错误。 Visual Studio没有任何报错,g++只是在一中情况下正确执行(也就是Example one的情况),但是上述的任意哪种写法都不应该同时出现在你的同一个代码文件中。

这篇关于C语言static的小问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆