Hi, i am new to C++ and while practicing i am getting an undefined reference error from the compiler and i dont know why... Can anyone see what the problem is below?
#include <iostream>
#include <iomanip>
using namespace std;
const int NUMBER_OF_ROWS = 6;
const int NUMBER_OF_COLUMNS = 5;
void printMatrix(int matrix[][NUMBER_OF_COLUMNS], int NUMBER_OF_ROWS);
void sumRows(int matrix[][NUMBER_OF_COLUMNS], int NUMBER_OF_ROWS);
void largestInRows (int matrix[][NUMBER_OF_COLUMNS], int NUMBER_OF_ROWS);
=== Build: Debug in Example 8-11 (compiler: GNU GCC Compiler) ===
In function `main':|
undefined reference to `printMatrix(int (*) [5], int)'
error: ld returned 1 exit status
=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===
The code is exactly as in the text book, can you explain why it is wrong?
Hello. Your function definition is different according to its declaration :)
You forgot something in your definition :
1 2 3 4
// your declaration
void printMatrix(int matrix[][NUMBER_OF_COLUMNS], int NUMBER_OF_ROWS);
// your definition ???
void printMatrix(int matrix[][NUMBER_OF_COLUMNS]) {...}
When you have a green wavy line on Visual Studio, often it means that you have no valid definition for a given declaration. Change you definition for this one and it works :
1 2 3 4 5 6
void printMatrix(int matrix[][NUMBER_OF_COLUMNS], int NUMBER_OF_ROWS)
{
int row;
int col;
// ...
}
17 8 24 10 28
9 20 16 55 90
25 45 35 8 78
5 0 96 45 38
76 30 8 14 28
9 60 55 62 10
Sum of row 1 = 87
Sum of row 2 = 277
Sum of row 3 = 468
Sum of row 4 = 652
Sum of row 5 = 808
Sum of row 6 = 1004
The largest element in row 1 = 28
The largest element in row 2 = 90
The largest element in row 3 = 78
The largest element in row 4 = 96
The largest element in row 5 = 76
The largest element in row 6 = 62
PS : Respectfully, it is better if you format your code according to the tag <code> as I did. Thanks ++
Part of the problem is that you have global: constint NUMBER_OF_ROWS = 6;
That value does not have to be global. It can be in main():
1 2 3 4 5 6
int main()
{
constint NUMBER_OF_ROWS = 6;
int board [NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
// ...
}
If you had had that, then compiler would have stopped at:
1 2 3 4 5 6 7 8 9 10 11 12
void printMatrix(int matrix[][NUMBER_OF_COLUMNS])
{
int row;
int col;
for (row = 0; row < NUMBER_OF_ROWS; row++) // ERROR: What is NUMBER_OF_ROWS?
{
for (col = 0; col < NUMBER_OF_COLUMNS; col++)
cout << setw(5) << matrix[row][col] << " ";
cout << endl;
}
}
There is also "masking":
1 2 3 4 5 6 7
constint NUMBER_OF_ROWS = 6; // global
void printMatrix(int matrix[][NUMBER_OF_COLUMNS], int NUMBER_OF_ROWS)
{
// NUMBER_OF_ROWS here is local variable, not the global.
// Someone could call this function with printMatrix( answer, 42 );
// ...
}