# include.h or .cpp file?

So, I have this strange problem: my main program generates an error message (undefined link to 'foo :: foo (int)') when I import the .h file into a separate class. However, when I change the import file to .cpp, everything works.

Now I read a little and saw a few video tutorials, and they all say the same thing: import the .h file. So why is this not working?

I use Code :: Blocks, where I compile and run (without the command line), on Windows 7. I suspect that something is not configured correctly, however I want to know for sure that my code does not work.

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; } 
+4
source share
3 answers

You need to compile both main.cpp and foo.cpp and link the 2 resulting object files together.

+1
source

You cannot compile and / or link the Foo.cpp file when you complete the link step. I am not familiar with Code :: Blocks, so I can’t say how to fix it.

+1
source

Right-click on the .cpp file and go to properties. On the Build tab, make sure compilation, link, debugging, and release are checked.

enter image description here

0
source

All Articles