Why static global variable is accessible in other file?

Viewed 105
//a.c
#include <stdio.h>
#include "b.c"
void main()
{
    int var;
    var = increment();
    var = increment();
    var = increment();
    count = count + 3;
    var = count;
    printf("%d", var);
}
//b.c
static int count;
int increment()
{
    ++count;
    return count;
}

Now as in b.c file I have a variable with name count and is static. Now this variable should not be accessible in a.c directly but in my case I can access and manipulate it. So am I missing something?

OUTPUT
6
2 Answers

#include "b.c" in a.c makes b.c a part of the compilation of a.c; they are compiled as one source file.

To keep identifiers in separate source files separate, you compile them separately, without using #include to include one in the other. The separate compilations produce separate object files (.o files on Unix and Unix-like systems), which you then link together with a link command (which may be included in or performed by the gcc command).

Separating the source files also separates an identifier you do want to share between the two files, the function named increment. So a.c will not know about increment, and the compiler will complain. To deal with this for a single function, you can simply declare the function in a.c with extern int increment();. However, the usual technique for managing this sharing of identifiers is:

  • Create a file named b.h that declares identifiers to be defined in b.c but shared with other source files.
  • In b.h, declare increment with extern int increment();.
  • In any source file that will use identifiers from b.c, include b.h with #include "b.h".
  • In b.c, also include b.h. This provides a check that the declarations in b.h match the definitions in b.c, because the compiler will see both while compiling b.c and report inconsistencies.

You've included b.c in a.c, so they become a single unit as far as the compiler is concerned. Because of this, you can see the static variable.

If you removed the include line, you wouldn't see either count or increment, although the latter would be implicitly declared because it is a function.

Related