1

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.

3
  • 2
    In func(), turn is supposed to be an object of type Turn. But there is no such object in scope there.You have the same issue in main(). You can create such an object in main: Turn turn; and then pass it to func() if you add a parameter. Commented Nov 2, 2024 at 13:18
  • 1
    This can't be C so I changed the tag Commented Nov 2, 2024 at 13:33
  • 1
    There is a season, extern Turn turn; Commented Nov 2, 2024 at 15:53

1 Answer 1

5

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;
};
Sign up to request clarification or add additional context in comments.

2 Comments

The answer is certainly useful, +1. But isn't it better to advocate adding Turn turn as a local in main (and pass it as an argument when needed), instead of using a global ?
@wohlstad True. I'd avoid global variables myself too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.