Reputation: 1376
How to declare static variable prior to its definition? The use case is there is other global variable is using it before it is defined. And I don't want to move the definition to top.
Example code:
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
Above code is compile error.
=== Update ====
Well, I found the solution myself. Just remove the extern
keyword.
Upvotes: 0
Views: 175
Reputation: 79
You cannot have two storage classes used on one single variable. Doing this will flag an error
Upvotes: 0
Reputation: 4034
Read http://www.learncpp.com/cpp-tutorial/43-file-scope-and-the-static-keyword/
In your example, the variable is declared static in the file scope. This means that it's available to all the code in the file.
In such a case it doesn't make sense to define it below the code that it uses. You should simply move it to the top of the file.
Also checkout Forward declaring static C struct instances in C++ if you have a need to do this for some reason. May be the solution provided there could be adapted to fit your larger goal.
Upvotes: 1
Reputation: 9841
You are trying to use two storage classes at a time. Thats problematic. Use static int a;
, and you can access it in your file, just make sure you are defining it above the code you are using it.
Upvotes: 2