PDA

View Full Version : problems with c and extern


alaios
07-18-2005, 06:51 PM
Hi i have some questions in c... If u can help me :)

a)I am trying to understand the extern.. Today i have faced the following problem
int main(){
int isvisible;
creates-1-thread();
creates-2-thread();
creates-3-thread();
}
I have written the code for each function in a separate file
creates-1thread.h etc
In each function i use the extern int isvisible; but still the compiler says that the variable is not declared :(
When i have changed the position of isvisible and put it below int main() everything got smoothly
int isvisible
int main(){
...
}

Why??? :(

aman
07-19-2005, 05:00 AM
Any variables you declare inside a function are local to that function. Variables declared outside of that function are global for that file, and can be accessed by other files by using the 'extern' keyword.

alaios
07-19-2005, 09:10 AM
Thx but threads usually share the same environments and the same variables... Thats why i cant understand why i should declare this variabla outside of the main fuinction and not inside

aman
07-19-2005, 09:21 PM
Well it's the same idea as calling another function from within your function. Function 2 has no idea what variables there are inside of function 1, just like thread a,b, or c has no idea what variables are inside of a function. Any variables you want to access in another function (or thread) need to either be passed to that function, or declared in global scope.

void functiona()
{
int a;

functionb();

pthread( callback );
}

void functionb()
{
a = 10; <-- functionb has no clue what variable 'a' is
}

int callback()
{
a = 10; <-- this thread's callback has no clue what variable 'a' is

return a;
}