Hi, As I was in the progress of learning 8051(specifically F340 uC from Silabs) with Keil C51 compiler. I came across this extern variable. This is what happen, hope somebody can enlighten me:
In the USB_HID example -> Blinky project, this variable USB_STATE was defined as unsigned char in F3xx_USB0_InterruptServiceRoutine.c, also in F3xx_USB0_StandardRequests.c this variable was externed, and this two file was part of the Blinky project.
Why not use only one extern variable? How C51 handle this thing? Why the compiler not complaining?
Thanks in advance.
regards gi
This is standard, textbook 'C' stuff - nothing specifically to do with Keil or C51.
In fact, it isn't even specific to 'C' - it is a general programming principle!
Some languages make it clearer by providing explicit keywords to distinguish the Definition - which actually causes memory to be consumed - and the Reference which, as the name suggests, simply refers to the object that has already been created.
F3xx_USB0_InterruptServiceRoutine.c
unsigned char USB_STATE; // This is the Definition; // This is what actually causes memory to be allocated.
F3xx_USB0_StandardRequests.c
extern unsigned char USB_STATE; // This is just a Declaration; // It just refers to memory already allocated elsewhere
c-faq.com/.../decldef.html
It would be better practice to use a so-called "header" file to share the reference.
It is also conventional to reserve names in ALL CAPITALS for #defines
Thanks Andy, Yes, I just noticed it, that variable is in 'c' file not placed in the header file. And so it is not in the macro #define so it should not be all capital, per se Thanks for your time in answering my question.
regards gp
Be careful. The extern does not specifically indicate a declaration.
extern unsigned char USB_STATE = 0; // This is the Definition; // This is what actually causes memory to be allocated