Quote:
|
Originally Posted by xrabohrok
Alrighty. I am pretty new to C, though not that new, and I have decided to attempt to try making my own libraries and attached .c files to see how they work. Through much thinking, I have decided to make a program that would simulate a blackjack deck. What I have here isn't very flexible, and it just draws five cards. But when I compile, it says everything in the .h file has been declared twice! I don't know what to do! Here's the code:
main.c
deck.c
deck.h
the board didn't keep any of the formatting. Sorry!
|
This is a common problem. Your variables are being declared in every file that includes them. So use it more than once....it defines them in multiple files.
In the file that needs to own them, in this case deck.c, flank the include statement with
#define VAR_DECLARE
the include
#undef VAR_DECLARE
Then in your header file, wrap all the code declaring the variables in
#ifdef VAR_DECLARE
code goes here
#else
extern code goes here
#endif
After the else copy your code defining the variables, but put extern in front of each, that means to the compiler "This is already declared elsewhere, use that version."
Example:
C file that owns header:
Code:
#define VAR_DECLARE
#include "header.h"
#undef VAR_DECLARE
C file that uses header, but does not own it:
Code:
#include "header.h"
Header file:
Code:
#ifdef VAR_DECLARE
char myChar1;
int myInt1;
#else
extern char myChar1;
extern int myInt1;
#endif