NoClueBlue
NoClueBlue

Reputation: 461

C++ - Getting undefined reference to my class

I have tried to find a solution to my problem online, but I've been unsuccessful. I think my problem may be related to linking.

I have 3 files scanner.h , scanner.cpp and scanner_test.h I've trimmed the files as best I can.

scanner.h

class Scanner {
public:
Token *scan (const char *);
};

scanner.cpp

#include "scanner.h"
Token scan(const char *text){
// Do something code
}

scanner_test.h

#include "scanner.h"
Scanner *s ;
void test_setup_code ( ) {
    s = new Scanner() ;
}
Token *tks = s->scan ( text ) ; //This line gives the error 

The error when I try to compile and run is from scanner_test.h undefined reference to `Scanner::scan(char const*)

This is my understanding of the code: scanner_test.h includes the scanner.h file which is linked to scanner.cpp during compilation and this file has the definition for Scanner::scan(char const*)

Upvotes: 2

Views: 1207

Answers (1)

Daniel Frey
Daniel Frey

Reputation: 56921

In scanner.cpp, you need:

Token* Scanner::scan(const char *text) { ... }
//     ^^^^^^^^^

otherwise you are implementing a free function called scan, not the member method from Scanner. (Note I also added the * you were missing, but the compiler will tell you this anyways once you added the Scanner:: part)

Upvotes: 8

Related Questions