Question

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);
}
Était-ce utile?

La solution 2

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.

Autres conseils

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.

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 .
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top