Global variables not getting initialized or may be corrupted

Tip / Sign in to post questions, reply, level up, and achieve exciting badges. Know more

cross mob
romac_285831
Level 2
Level 2

 Hi,

   

I am using a global variable x, declaring it in some c1 file. This c1 file has an  interrupt code. x is altered on interrupt.

   

Now in some  c2 file i am using this x

   

extern x ;

   

But the x is never seen altered in C2 even it is being altered in C1 file when interrupt comes.

   

I have used OCD  to verify this.

   

Now if i put the entire C1 file code into c2 file to avoid this extern, it works fine. 

   

What is the scope and lifetime  of global variable?

   

How do i communicate between files.

   

I spent a whole day on this crap. 

0 Likes
4 Replies
romac_285831
Level 2
Level 2

 Found the mistake

   

 

   

I was doing

   

extern variable_name;

   

But it should be

   

extern datatype variable_name ;

   

eg.

   

BYTE x;

   

extern BYTE x;

0 Likes
Bob_Marlowe
Level 10
Level 10
First like given 50 questions asked 10 questions asked

... and you may spend some more days, with such a fricken bug.

   

 

   

I can assure you that your environment as you described it will run as expected.

   

 

   

When reducing your code to the absolute necessary (a main.c with the variable declared as volatile extern and inspecting it, a second file with a timer-isr incrementing that global var here).

   

 

   

Did you qualify your variable as volatile? Have a look here in my favourite online C-manual what it is for: http://publications.gbdirect.co.uk/c_book/chapter8/const_and_volatile.html

   

 

   

Bob

0 Likes
Anonymous
Not applicable

When we don't declare a datatype for a variable, compiler assumes it as "int" - a 2 byte variable. In c2 file, it is being treated as "int". This will cause problems. For instance, if you try to copy this variable to a byte type variable, it will take the data from a (address+1) location of "int" variable; but the data will be actually in (address).  Try it out with a simple program and look into the .lst file. 

0 Likes
ETRO_SSN583
Level 9
Level 9
250 likes received 100 sign-ins 5 likes given

The size of INT is compiler dependent,and varies in ANSI from one revision level

   

to another. Basically stating an INT should be close to the HW implementation of

   

the machine. In Imagcraft and HiTech 16 bits.

   

 

   

I saw a reference current ANSI is 4 bytes for a 32 bit platform.

   

 

   

The only relevancy this has to PSOC 1 is porting in and out of PSOC 1.

   

 

   

Regards, Dana.

0 Likes