Using a static variable or function in various files. - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Using a static variable or function in various files.

shantanukshantanuk Posts: 13Member
Hi,
Suppose we have declared a static variable or function in one of the source files and now we wish to use same variable or function in other source file, how do we use this?
_shantanuk.

Comments

  • LundinLundin Posts: 3,711Member
    : Hi,
    : Suppose we have declared a static variable or function in one of the source files and now we wish to use same variable or function in other source file, how do we use this?
    : _shantanuk.
    :


    You can't. The whole purpose of static variables is to block other files from using them.

    You must do like this, which is also good programming practice:

    [code]
    /* myfile.h */

    int getMyVar (void);
    [/code]

    [code]
    /* myfile.c */
    #include "myfile.h"

    static int myVar;

    int getMyVar (void)
    {
    return myVar;
    }
    [/code]

    [code]
    /* main.c */

    #include "myfile.h"

    int main()
    {
    printf("%d
    ", getMyVar());
    return 0;
    }
    [/code]
Sign In or Register to comment.