I have a const char array defined in a .c file. I have a .h associated with the .c file included in my main file. Can i use that array in my main file? Do i have to define it in my main.c file and my other file(card.c)?
I have a const char array defined in a .c file. I have a .h associated with the .c file included in my main file. Can i use that array in my main file? Do i have to define it in my main.c file and my other file(card.c)?
extern type arrayname[ ARRAYSIZE ];
Put that in your header file, and include the header file wherever you want to use it.
Quzah.
Hope is the first step on the road to disappointment.
As long as the array is global in that .c file, copy the declaration to the .h file, and put the word "extern" in front of it:
Then, include that .h file in your main file, and you can access the array. Note that global variables are evil and should be avoided wherever possible.Code:extern const int array[10];
Thanks, I put extern in front of the definintion in the .h file and tried to compile. This is what i got, im not sure what it means.
I understand the first 4 lines are issuing warnings about using global variables, but i dont understand what the last 3 lines are saying.Code:In file included from Card.c:11: Card.h:17: warning: ‘ranks’ initialized and declared ‘extern’ In file included from Main.c:8: Card.h:17: warning: ‘ranks’ initialized and declared ‘extern’ /tmp/ccB8elgO.o:(.rodata+0x0): multiple definition of `ranks' /tmp/ccNOr1zb.o:(.rodata+0x0): first defined here collect2: ld returned 1 exit status
You need to recompile everything that has your .h included any time you change it.
Quzah.
Hope is the first step on the road to disappointment.
It's hard to say exactly what the problem is without your code, but here's a guess:
Don't put initializers in the .h file. The header should have a declaration only. Put them in the .c file that has the definition. Read up on the difference between declaration here: Declaration vs definition. Prelude's comment in post #7 is a good, brief explanation.
Example of how it should be:
Code:/* card.c */ int ranks[13] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; ... /* card.h */ extern int ranks[13]; /* main.c */ #include "card.h" // do something with ranks
That worked, thank you.