ppappiya
ppappiya

Reputation: 13

about static variable initializing and scope

I have problem with a static variable.

I tried to make maze program by using stack.

At first, it activates currently when I put all codes in same source file.

But after I separate main to main.c source, and other functions to function.c, an error occurred at static variable.

This is part of code in function.c file that problem happen.

I used EXIT_ROW and EXIT_COL as static variable, and these initialized at main function. And I use EXIT_ROW and EXIT_COLS at other function.c file but when I do debugging this file, EXIT_ROW and EXIT_COL didn't initialize at all.

void main()
{
    int xsize, ysize;
    FILE *fp;
    if( !( fp = fopen("input.txt", "r") ) )
    {
        fprintf(stderr, "FILE couldn't open\n");
        exit(EXIT_FAILURE);     

    };

    fscanf(fp, "%d %d", &ysize, &xsize);
    EXIT_ROW = ysize;
    EXIT_COL = xsize;
    printf("%d %d\n", ysize, xsize);

    init_maze(xsize, ysize, fp);

    print_maze(xsize, ysize);

    path();
}

I couldn't understand why it happened.. EXIT_ROW and EXIT_COLS are declared in stack.h header file. can u help me why it happened, and how can I fix it?

Upvotes: 1

Views: 51

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

I can assume that you defined the variables with the internal linkage and with file scopes. So each translation unit has its own set of these varaibles.

Any initialization of these variables in one translation unit does not influence on the variables in other translation unit.

Remove keyword static in the declaration of the variables. Declare them in some header with keyword extern and define them only in one translation unit.

Upvotes: 1

Related Questions