I have a global bariable defined, and I want one of the functions in the project to use it. I just used it in the function but I get an error 'vars' : undeclared identifier.
Do I have to pass a global variable to a function to use it?
Printable View
I have a global bariable defined, and I want one of the functions in the project to use it. I just used it in the function but I get an error 'vars' : undeclared identifier.
Do I have to pass a global variable to a function to use it?
No, but you do have to declare the global variable higher than its first use.
Yep, they are declared at the top of the program. The function I'm trying to use it in is is a separate .c file, if I use the varriable in the file .c file, it's fine.
In the separate .c file, add the line extern int vars; or whatever type it is. Anyway, declare it like you did your global variable but prepend the keyword extern to it.
if I use extern int vars, will that create a new instance of vars? Because I want to use the other vars that is created in the main file. It's a structure and I want to use some of the entries in it.
No, it just tells the compiler "Hey, this is declared in another file" so the linker doesn't barf. It's the same variable so changing it in one .c file changes it in the other.
The extern worked.
thanks,
as.