stactic variable is shared as global variable

Hi,

I have doubt about static variables declared in a header, if I declare the variable "numero" as static global variable in a header file (arch2.h) , then every process inside arch2.h can use the static variable numero, but i can't be used in other file,rigth?

below part of code

header arch2.h
1
2
3
4
5
6
7
// declare the static variable
static int numero = 64;

void fun1(){

	if(numero ==2)numero =12;
}


and in the main.cpp
1
2
3
4
5
6
7
8
#include "arch2.h"

void main(){
  
   if(numero ==64){
	numero =2;}
   fun1();
}


everything compiles and when I execute and debug the program, the "main" recognize the static variable "numero" and its initialization value which is declared in "arch2.h",and when the variable "numero" change its value to 2, when it call the function fun1() it see the variable "numero" with a value equal 2, in that case "static int numero" works as global variable??, if my understanding about static variable is wrong please correct me.
I'm using Visual C++ 2010

Problem in that is that you only compile one file: the main.cpp.

Preprocessor evaluates the include directives before compilation, and therefore the code that to you is in two files, is just one piece of text for the compiler.
static limits the visibility of the variable to the compilation unit. Your compilation unit is main.cpp. arch.h is not a compilation unit. It is a header file that is included within a compilation unit.

If you had another compilation unit, say func.cpp, which also included arch2.h, you would have two separate instances of numero. Changing the value of numero in one compilation unit would not affect the value in another compilation unit.

Thanks for your answer,
so what can i do to make understand to the compiler they are two files?, create a file called arch2.cpp?
thanks in advance
What are you trying to accomplish?
Why are you declaring numero as static?

BTW, it's poor style to put a function in a header file. If you do so, and you include that header file in more than one compilation unit, the linker will give you errors due to a multiply defined function.

If your intent was to share fun1 across multiple compilations, then yes, you should put it in it's own .cpp file.
That I was trying is only see how works static global variable in a header and that this static variable cannot be acces from another files, and also see when main.cpp include the header "arch2.h", the main.cpp can use the "static int numero" only for the main.cpp besides the "static int numero" from "arch2.h"

thanks for your answer,
now i have a better idea how static works and how shoud write the code using header files,all header files should have only declaration of variables and funtions and the initialization of variables and definition of function only in .cpp files,if I'm wrong pls correct me

thanks in advance
Topic archived. No new replies allowed.