First of all, in turn.h
you should declare the enum using a typedef like this:
#ifndef TURN_H
#define TURN_H
typedef enum {
WHITE,
BLACK
} Turns;
typedef struct {
Turns turn;
} Turn;
void setTurn(Turn *t, Turns newTurn);
Turns getTurn(Turn *t);
void changeTurn(Turn *t);
Turn turn; // This allows main to see the struct declared in turn.cpp
#endif
As you can see in code above, to solve your problem, I also added Turn turn;
to turn.h
. This allows main.cpp
to see the struct you want to declare in turn.cpp
. Then, remove extern Turn turn;
from turn.cpp
because it has no effect.
Then, modify turn.cpp
like this:
#include "turn.h"
Turn turn;
void setTurn(Turn *t, enum Turns newTurn) {
t->turn = newTurn;
}
enum Turns getTurn(Turn *t) {
return t->turn;
}
void changeTurn(Turn *t) {
if (t->turn == WHITE) {
t->turn = BLACK;
} else {
t->turn = WHITE;
}
}
Note:
The keyword extern
looks for declarations of the variable or function passed as its argument outside the file in which the extern is. Putting it inside turn.cpp
isn't useful because Turn turn;
is declared in itself. You should put the extern if the file which doesn't have the declaration inside,
I want to specify that typedef is not mandatory for the enum:
#ifndef TURN_H
#define TURN_H
enum Turns {
WHITE,
BLACK
};
typedef struct {
enum Turns turn;
} Turn;
void setTurn(Turn *t, enum Turns newTurn);
enum Turns getTurn(Turn *t);
void changeTurn(Turn *t);
Turn turn;
#endif
As you can see, it works also without typedef.
However, everytime you declare a Turns
you have to use the syntax enum Turns
, which is verbose and less readable. If you want to modify all declarations of the enum across all your files.