3

I have already checked StackOverflow to find the solution to my problem, but I think I might be missing something. I am trying to define a class in a header file (.h) and implement its methods in a cpp file (.cpp), but it does not work.

main.cpp:

#include <iostream> #include "Message.h" using namespace std; int main() { Message *t = new (Message); t->display(); return 0; } 

Message.h:

#ifndef MESSAGE_H_INCLUDED #define MESSAGE_H_INCLUDED class Message { public: void display(); }; #endif // MESSAGE_H_INCLUDED 

Message.cpp:

#include "Message.h" void Message::display() { cout << "Hello!"; } 

I don't understand why I keep getting the following error

undefined reference to 'Message::display()' 
5
  • 3
    How do you compile this? Commented Aug 15, 2015 at 22:23
  • 3
    Your code is correct (aside from the memory leak). Message.cpp is not getting linked - possibly not compiled. Commented Aug 15, 2015 at 22:24
  • I am using CodeBlocks (GNU GCC Compiler), with the flags: -O2, -ansi, -Wall and -pedantic Commented Aug 15, 2015 at 22:29
  • CodeBlocks will show you the compilation command being run. Show us, please. Commented Aug 15, 2015 at 22:34
  • Thank you, I just fixed it. It was a compiling error, I solved it by going through Project->Properties...->Build Targets and then selecting all the files in the bottom section! Commented Aug 15, 2015 at 22:39

1 Answer 1

2

Compile this with the command g++ -std=c++11 Message.cpp main.cpp

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.