Search code examples
c++cstaticdefinition

How to declare a static variable but not define it


Some times we need to pre-declare a static variable and then use it. But the variable name of this declaration may be wrong, and the compiler can not detect it, oops!

Example:

/* lots of codes */
static some_type some_name; /* pre-declaration */
                            /* but it may define "some_name" */
/* use some_name */

/* lots of codes */

static some_type someName = initialization; /* definition */
/* use someName */

/* lots of codes */

"some_name" and "someName" are different, we use a wrong variable at the begin. If the pre-declaration statement does not define any thing, the compiler will detect the mistake.

So, how to declare a static variable but not define it? How can I change the pre-declaration to a new one which makes compiler can detects wrong names?


Solution

  • gcc will give a warning in the case you've described:

    ./x.c:3010: warning: 'someName' defined but not used
    

    Solution: Do what you're currently doing, but don't ignore compiler warnings ;)

    Edit:

    With your updated question: No, I don't believe there is a way to simply declare a static variable (without also defining it).

    The common solution is just to make sure all your global scope variables are declared once only, with an initialiser if they need it.