1

I am trying to seperate references, functions, and a main function into a .h and 2 .cpp files for the first time and cannot get the functions referenced in my object.h file and defined in my object.cpp file to work in my main.cpp.

I am using codeblocks to create a project, Creating a console application, creating a class within that project including .h and .cpp files made within the same folder. I then copy #include and namespace into my cpp file below #include "object.h". I then define a simple function to cout a string in .cpp copy paste the reference into .h . Then I go back to main and create an object for the function. then I call the function with the newly created object. It is at this point that my code will no longer compile.

// This is main.cpp

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

using namespace std;

int main()
{
  object thing;

  thing.printObject();
  return 0;
}

// This is object.cpp

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

using namespace std;

  void printObject(){

  cout << "You rock!" << endl;

}

// This is object.h

#ifndef OBJECT_H
#define OBJECT_H

class object
{
public:
  void printObject();
};

#endif 

And this is the output I get during build:

obj\Debug\main.o||In function `main':|
D:\c ++\Object test\main.cpp|11|undefined reference to 
`object::printObject()'|
||error: ld returned 1 exit status|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) 
===|

I expected my console would print "You rock!".

1

1 Answer 1

2

In the cpp-file you should have

void object::printObject() {

otherwise you define a global function, not a method of object.

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

2 Comments

Thank you so much. I knew to do that but somehow I hadn't been an any of my attempts. Works now.
Glad I could help. You did a good job of clearly stating your first question at SO. It would be nice if you could also accept the answer (so that other people can immediately see that this question was answered).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.