Reputation: 1447
So I have this weird looking problem: my very basic program generates an error message (undefined reference to 'foo::foo(int)') when i import the .h file of a separate class. However, when I change the import file to .cpp, it all works.
Now, I've read a little, and seen a few video tutorials, and they all say the same: import the .h file. So why doesn't it work?
I use Code::Blocks, where i compile and run(no command lines), in Windows 7. I do suspect that something isn't set up quite right, however, I do want to know for sure if it is my code that fails.
Main.cpp:
#include <iostream>
#include "Foo.h" //This don't work. If i include Foo.cpp it does.
using namespace std;
int main()
{
Foo k(10);
cout << k.getInt() << endl;
}
foo.h:
#ifndef FOO_H
#define FOO_H
class Foo
{
public:
Foo(int tall);
int getInt()const;
protected:
private:
int m;
};
#endif
Foo.cpp:
#include "Foo.h"
Foo::Foo(int tall)
: m(tall)
{
//ctor
}
int Foo::getInt()const
{
return m;
}
Upvotes: 4
Views: 4998
Reputation: 53037
Right-click on your .cpp file and go to properties. On build tab make sure compile, link, debug, and release are checked.
Upvotes: 0
Reputation: 109119
You need to compile both main.cpp and foo.cpp and link the 2 resulting object files together.
Upvotes: 2
Reputation: 8968
You are failing to compile and/or link the Foo.cpp file when you do your linking step. I'm not familiar with Code::Blocks though, so I can't tell you how to fix it.
Upvotes: 1