c++structenumsglobal-variables

How to access a struct from another file?


I have the following code and the objective is to make use of the colour variable as a binary flag in the code.

main.cpp

#include "turn.h"
#include <stdio.h>

void subfunc(Turns t) {
    printf("%d\n", t);
}

void func() {
    Turns colour = getTurn(&turn);
    subfunc(colour);
}

int main() {
    setTurn(&turn, WHITE);
    func();
    return 0;
}

turn.cpp

#include "turn.h"

extern Turn turn;

void setTurn(Turn *t, Turns newTurn) {
    t->turn = newTurn;
}

Turns getTurn(Turn *t) {
    return t->turn;
}

void changeTurn(Turn *t) {
    if (t->turn == WHITE) {
        t->turn = BLACK;
    } else {
        t->turn = WHITE;
    }
}

turn.h

#ifndef TURN_H
#define TURN_H

enum Turns {WHITE, BLACK};

typedef struct {
    Turns turn;
} Turn;

void setTurn(Turn *t, Turns newTurn);
Turns getTurn(Turn *t);
void changeTurn(Turn *t);

#endif

Unfortunately this code gives me an error stating that turn was not declared in the main.cpp scope.


Solution

  • extern Turn turn; is neither declared visibly in main.cpp nor defined anywhere, so the program will fail to link if you make the declaration visible.

    Move extern Turn turn; to turn.h and in turn.cpp, define it:

    Turn turn;
    

    Note: You do not need to typedef your classes in C++. This will suffice:

    struct Turn {
        Turns turn;
    };