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!".

  • Possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Alan Birtles Aug 02 '19 at 06:29

1 Answers1

2

In the cpp-file you should have

void object::printObject() {

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

Gerriet
  • 1,302
  • 14
  • 20
  • Thank you so much. I knew to do that but somehow I hadn't been an any of my attempts. Works now. – Nicklandreth Aug 02 '19 at 04:56
  • 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). – Gerriet Aug 02 '19 at 05:02