如何在C中声明尚未定义的静态变量

时间:2014-06-04 04:00:04

标签: c compiler-construction static extern

如何在定义之前声明静态变量?用例是在定义之前有其他全局变量正在使用它。而且我不想将定义移到顶部。

示例代码:

extern static int a; //compiler error, but I need to declare 'a' because it is used below by 'x'

typedef struct{
 int * dd;
}X;

static X x={&a}; //this variable needs to use 'a'

static int a=5; //this is where 'a' defined

上面的代码是编译错误。

===更新====

好吧,我自己找到了解决方案。只需删除extern关键字。

3 个答案:

答案 0 :(得分:2)

您尝试一次使用两个storage classes。这有问题。使用static int a;,您可以在文件中访问它,只需确保将其定义在您使用它的代码之上。

答案 1 :(得分:1)

阅读http://www.learncpp.com/cpp-tutorial/43-file-scope-and-the-static-keyword/

在您的示例中,变量在文件范围中声明为static。这意味着它可用于文件中的所有代码。

在这种情况下,在它使用的代码下面定义它是没有意义的。您只需将其移动到文件的顶部即可。

如果由于某种原因需要执行此操作,请结帐Forward declaring static C struct instances in C++。如果可以适应您的更大目标,可能是解决方案。

答案 2 :(得分:0)

您不能在一个变量上使用两个存储类。 这样做会标记错误