Undefined error - but I added the header file OK

Hello C++ professionals, I am getting an error below. I have searched online for this solution, but I cannot see where the problem is since I added the header file accordingly to the .cpp files. Can you help me please.
Error is:

CMakeFiles\untitled23.dir/objects.a(main.cpp.obj): In function `main':
C:/Users/CLionProjects/untitled23/main.cpp:8: undefined reference to `Mypuzzle::size()'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: *** [CMakeFiles\untitled23.dir\build.make:85: untitled23.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles\Makefile2:72: CMakeFiles/untitled23.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:84: CMakeFiles/untitled23.dir/rule] Error 2
mingw32-make.exe: *** [Makefile:117: untitled23] Error 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//============main.cpp========
#include <iostream>
#include "mypuzzle.h"

using namespace std;

int main() {
    Mypuzzle puzzle;
    puzzle.size();
    return 0;
}
//===== mypuzzle.h
#include <iostream>


class Mypuzzle {
    private:
        int icount; 

    public:
        friend std::istream&  operator>>(std::istream& in, Mypuzzle& puzzle);
        int size();
};
//======mypuzzle.cpp===============================
#include "mypuzzle.h"
#include <iostream>

using namespace std;

Mypuzzle::Mypuzzle() {

}

istream & operator>>(istream& in, Mypuzzle& puzzle)
{
    char u_input;
    while (count < 81) {
        in >> u_input;
        if (isdigit(u_input)) {
            cout << u_input;
            if (isdigit(u_input)==0) {
                  icount++;
        }
    }
}

int Mypuzzle::size() {
    
    return icount;  //<== Ultimate goal is to return this counter
}
Last edited on
You need to add mypuzzle.cpp as a source file in your make file.
That's a linker error. It has nothing to do with the header file. It's telling you that the linker can't find the definition of Mypuzzle::size() anywhere in the compiled object code. This means that your project doesn't have any way of linking against the object code compiled from mypuzzle.cpp .

As salem c says, you can fix this by adding mypuzzle.cpp to your ptoject.

Also, note that your line 9 does nothing, because you're not actually doing anything with the value returned from Mypuzzle::size().
Topic archived. No new replies allowed.