Reputation: 45
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!".
Upvotes: 1
Views: 2583
Reputation: 1350
In the cpp-file you should have
void object::printObject() {
otherwise you define a global function, not a method of object.
Upvotes: 2