Reputation: 13
I want to define an array with the size of 1 byte that is available for several .c files, thus I need a global array. I know the way for global variables:
//"globals.h"
extern uint8_t GlobalVar; //Declaration
//"globals.c"
uint8_t GlobalVar = 0; //Definition
So, for my array I first used typedef to define a byte:
typedef uint8_t byte; //in "globals.h" right at the beginning
Then I proceed with declaration and definition of my array:
//"globals.h"
extern byte GlobalAr[10];
//"globals.c"
byte GlobalAr[0] = 0b00001111;
But then I get these errors:
Error 1 conflicting types for 'GlobalAr'
Message 2 previous declaration of 'GlobalAr' was here
Error 3 invalid initializer
If I try the same thing within a function it works perfectly fine i.e.:
typedef uint8_t byte;
void function()
{
byte GlobalAr[10];
GlobalAr[0] = 0b00001111;
GlobalAr[1] = 0b11110000;
}
Q1: Can you guys help me figuring out how to define a global array and to initialize it properly?
Q2: Why does the second way work but the first one doesn't?
Would appreciate any kind of help! Thanks in advance!
Upvotes: 0
Views: 7197
Reputation: 134286
I think, you missed to define the array.
IMO, what you want is
byte GlobalAr[10] = {0};
GlobalAr[0] = 0b00001111;
GlobalAr[1] = 0b00001010;
and so on.
Otherwise, as per your code
extern byte GlobalAr[10];
and
byte GlobalAr[0] = 0b00001111;
you're trying to redefine the GlobalAr
array with a different size[10
vs 0
], which is wrong.
Also, if you really want an array of one element only, you have to change the declaration and the definition to
byte GlobalAr[1] = {0b00001111};
and while accessing , you can use GlobalAr[0]
.
Upvotes: 1
Reputation: 141554
To declare the array in your .h file:
extern uint8_t GlobalVar[1];
In exactly one .c
file (which should include that .h
file, in order to generate a compilation error if you have a mismatch) must have the definition:
uint8_t GlobalVar[1] = { 0x0F };
0b00001111
is not valid in C, I assume this is supposed to be 0x0F
.
The difference with your "code in function" example is that functions may contain both declarations and statements. In that function you declare an array with no initializer, and then use assignment statements to give values to it.
Outside of a function this is not possible; you can only provide initializers as part of the definition, and for an array they take the form of =
followed by a brace-enclosed list which is inserted just before the ;
at the end of the definition.
Upvotes: 1
Reputation: 2172
This line is completely wrong:
byte GlobalAr[0] = 0b00001111;
Compiler thinks you are going to:
If you want to define array and initialize its elements you MUST enclose them inside {}
byte GlobalAr[10] = {0b00001111, 0b11110000};
It is not possible to change elements of array in file scope as you attemted to. You need to place such code in a function.
Upvotes: 1