c++ - Redefined variable in the other module -


Why do we redefine the variable in other modules, so it is OK to add this module together? I have written two modules main.cpp and module.cpp as the following:

  // - main.cpp-- // # include & lt; Stdio.h & gt; Int main () {int i = 5; Printf ("I value is% d", i); }   

and

  // - module.cpp - // int i = 7;   

I am now compiling and adding g ++ as the following:

  g ++ -c main .cpp g ++ - c module. cao g ++ - o bin main.o module.o   

and it's okay. But I hope the compilation will be successful, while the linker will throw an exception like redefining varaible when I'm running .bin output then the value of i is 5 .

UPD: I understand that if we use I as global variable module main.cpp that linker will throw an error.

The main variable in the function is a local variable of i function. It is not visible and is present outside the function is.

Consider the following example

  #include & lt; Iostream & gt; Int i = 3; Int main () {int i = 10 std :: cout & lt; & Lt; "I =" & lt; & Lt; I & lt; & Lt; Std :: endl; Std :: cout & lt; & Lt; ":: I =" & lt; & Lt; :: I & lt; & Lt; Std :: endl; I = :: i; Std :: cout & lt; & Lt; "I =" & lt; & Lt; I & lt; & Lt; Std :: endl; Std :: cout & lt; & Lt; ":: I =" & lt; & Lt; :: I & lt; & Lt; Std :: endl; {Int i = 20; Std :: cout & lt; & Lt; "I =" & lt; & Lt; I & lt; & Lt; Std :: endl; Std :: cout & lt; & Lt; ":: I =" & lt; & Lt; :: I & lt; & Lt; Std :: endl; } Std :: cout & lt; & Lt; "I =" & lt; & Lt; I & lt; & Lt; Std :: endl; Std :: cout & lt; & Lt; ":: I =" & lt; & Lt; :: I & lt; & Lt; Std :: endl; }   

Local variables have no relation.

Comments

Popular posts from this blog

Pass DB Connection parameters to a Kettle a.k.a PDI table Input step dynamically from Excel -

multithreading - PhantomJS-Node in a for Loop -

c++ - MATLAB .m file to .mex file using Matlab Compiler -