Variable Scope issue

Status
Not open for further replies.

haxan

New Member
Hi. I am having an issue with variables and their scope. How can i access variables directly which are in one C file to another C file in the same project?

For example i have two C files, code1.c and code2.c

Some variables that i declared in code1.c i want to use directly into code2.c

Is there anyway to do it?


Example:

code1.c:

unsigned char myVariable = 24;


code2.c:

#include "code1.c"
myVariable = myVariable + 2;
 
Last edited:
code2.c:

#include "code1.c"
myVariable = myVariable + 2;

You mean #include "code1.h", right? In code1.h you just declare myVariable as extern. e.g.
Code:
extern unsigned char myVariable;
 
I think you misunderstood.

code1.h (declare the variable as being held somewhere else)
Code:
extern unsigned char myVariable;

code1.c (define and initialise the variable as belonging to this file)
Code:
unsigned char myVariable = 0;

code2.c (includee the extern decl and then do something with the variable from the other file)
Code:
#include "code1.h"
... something ...
myVariable = 33;
 
Thank you, its been solved now.

Following is the correct method for someone who falls in the same place as me.



code1.C:
unsigned char myVariable;
myVariable = 2;


code2.C:
extern volatile unsigned char myVariable;
myVariable = 5;

The code2.c can now access the same variable.
 
I'm guessing the 'volatile' keyword was inadvertently added in the first instance.
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…