Search code examples
c++includepreprocessor

C++: error, multiple definition of variable


Getting error message saying: SudokuGame\sudoku_solver.h:6: error: multiple definition of `grid'

Can anyone point out why? I guess i'm including sudoku_solver.h in the wrong way

See parts of my code files below.

sudoku_solver.cpp:

#include <iostream>
#include "sudoku_solver.h"

using namespace std;

bool isPresentInCol(int col, int num) {
        for (int row = 0; row < N; row++)
                if (grid[row][col] == num)
                        return true;
        return false;
}

sudoku_solver.h:

#ifndef SUDOKU_SOLVER_H
#define SUDOKU_SOLVER_H

#define N 9

int grid[N][N] = {
   {3, 0, 6, 5, 0, 8, 4, 0, 0},
   {5, 2, 0, 0, 0, 0, 0, 0, 0},
   {0, 8, 7, 0, 0, 0, 0, 3, 1},
   {0, 0, 3, 0, 1, 0, 0, 8, 0},
   {9, 0, 0, 8, 6, 3, 0, 0, 5},
   {0, 5, 0, 0, 9, 0, 6, 0, 0},
   {1, 3, 0, 0, 0, 0, 2, 5, 0},
   {0, 0, 0, 0, 0, 0, 0, 7, 4},
   {0, 0, 5, 2, 0, 6, 3, 0, 0}
};

/*
*Check if number is present in given coloum
*/
bool isPresentInCol(int col, int num);

/*
*Check if number is present in given row
*/
bool isPresentInRow(int row, int num);

#endif // SUDOKU_SOLVER_H

main.cpp:

#include "sudoku_solver.h"
#include <iostream>
using namespace std;

int main()
{
    if (solveSudoku())
        printSolvedSudoku();
    else
        cout << "No solution exists";

    return 0;
}

Solution

  • sudoku_solver.h is included in both sudoku_solver.cpp and main.cpp. Hence two definitions of the global variable grid.