3

I'm wondering why is this code compiles and run. I thought that if a variable is declared as static (in global scope) it will be accessible only within the file it is declared.

functions.h

static int x = 10;

main.c

#include <stdio.h>
#include "functions.h"

extern int x;

int main()
{
   printf("%d", x);
}
DRON
  • 93
  • 1
  • 5

3 Answers3

1

Technically, it is indeed declared within the main.c, as this includes the functions.h. If it was a sparate compilation module, you'd be right.

But I'd have suspected that within the same compilation unit extern and staticwould collide with each other. At least it would be worth a warning.

glglgl
  • 89,107
  • 13
  • 149
  • 217
  • 1
    A declaration with `extern` following a declaration with `static` that is in scope adopts the `static`, per C 2011 (N1570) 6.2.3 4: “For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible, if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration.” – Eric Postpischil Dec 04 '13 at 12:17
  • @EricPostpischil That was new to me, thank you. Are there any useful usecases for this? – glglgl Dec 05 '13 at 08:16
0

The preprocessor takes the text in functions.h and copies it as is into main.c After preprocessing (and before compilation) your main.c looks as follows:

#include <stdio.h>
static int x = 10;

extern int x;

int main()
{
   printf("%d", x);
}

You will have linker problems if functions.h is included into a second source file, and you try to link both object files into one executable.

MichaelMoser
  • 3,172
  • 1
  • 26
  • 26
  • Linker problems? `functions.h` can be included in any number of files without a linker problem because `static` variable names aren't visible to the linker. – Klas Lindbäck Dec 04 '13 at 08:43
  • correction: for gcc: In c++ there is a linker error (multiple definitions of x) if int x; is defined in two different source files, and both object files are linked together (in C that is just fine); if static int x; is in both source files then that is not a linker error. – MichaelMoser Dec 09 '13 at 19:23
  • `extern` and `static` are contradictory so combining them is a bad idea. – Klas Lindbäck Dec 10 '13 at 08:06
-1

when you are including functions.h in main.c , you are actually copy content of function.h in main.c so your final code become something like :

#include <stdio.h>
static int x = 10;

extern int x;

int main()
{
   printf("%d", x);
}

So your extern line is redundant. you can achieve what you want by this remove #include "functions.h" from main.c

  1. compile function.h using g++ -c function.h
  2. compile main.c using g++ -c main.c
  3. then build g++ function.o main.o -o out third line would not compile because of static int .
EmptyData
  • 2,386
  • 2
  • 26
  • 42