class call funtion

hi there,

I have two header files
Form.h and serial.h

in Form.h I declare and call a class like this:

CRC df1;
crc = df1.CHECK(crc,buffer[6]);

serial.h
class CRC {
public:
int x,y;
unsigned char CHECK (unsigned char cPrev, unsigned char cNext)
{
unsigned char cNew = (cPrev << 1) & 0xFF;
if(cPrev & 0x80)
{
cNew --;

}
cNew ^= cNext;
return cNew;
}
};

when I compile this it runs it but when I debug it it seems never to call the method CHECK can anyone explain what I do wrong?

Many thanks
...
Last edited on
crc is declared in Form.h as a unsigned char crc =0;
anyone ?
Maybe I'm stating the obvious, but since you placed it in the beginner forum, let me ask:

Are you sure it's not calling CHECK? I mean, can't it be it's just not giving you the output you expect?

does this code generate the text "check is called" ?
1
2
3
4
5
6
7
unsigned char CHECK (unsigned char cPrev, unsigned char cNext) {
    std::cout << "check is called\n";
    unsigned char cNew = (cPrev << 1) & 0xFF;
    if(cPrev & 0x80)
    {
        cNew --;
    }
No i have added a break point inside the CHECK method and this point is never reached.

please help me out
Hi Jorz,

I'm also a beginner, so you might find a better explanation. But I think the problem is as follows.

You are using an external variable called "crc".

An external variable must be defined, exactly once, outside of any function; this sets aside storage for it. The variable must also be declared in each function that wants to access it; this states the type of the variable. The declaration may be an explicit extern statement or may be implicit from context.

Now what happened is this:
in form.h you declared & defined crc unsigned char crc=0;
In main you are defining it yet again:
crc = df1.CHECK(crc,buffer[6]);

This is not allowed.

One way to prevent it is by making the variable static.
If you make the following change in Form.h your code should work:
static unsigned char crc=0;

This way you force that it is only initialized (defined) once.

Another option is to move the crc definition to the main cpp file.
in Form.h you'd write:
extern unsigned char crc;

in the main.cpp file you write:
unsigned char crc=0;

---

To me one question remains (like I said I'm a beginner too). I don't know why it's not allowed to do it exactly the other way around. Why it is that I cannot say in the main.cpp
extern unsigned char crc;
and in form.h unsigned char crc=0;

Maybe this has to do with the order in which the linker treats the definitions & declarations? I would love to know why..

Last edited on
Topic archived. No new replies allowed.