undefined reference to class function

Please tell me how to compile this code.
main.cpp and DerClass files are in different directories.

main.cpp
1
2
3
4
5
6
7
8
#include <DerClass.h>

int main()
{
	DerClass der1;

	der1.fn();		//undefined reference to `DerClass::fn()'
}


lib/DerClass.h
1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef DERCLASS_H
#define DERCLASS_H

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

	class DerClass
	{
		public:
			void fn();		//this not compile
			//void fn() { std::cout << " DerClass"; } //this works
	};
#endif 


lib/DerClass.cpp
1
2
3
#include "DerClass.h"

void DerClass::fn() { std::cout << " DerClass"; }


The file locations are:
1
2
3
inherit/main.cpp
inherit/lib/DerClass.h
inherit/lib/DerClass.cpp


Maybe the g++ command is off:
C:\Users\wolf\Documents\demo_MinGW\inherit>g++ -Wall -Ilib main.cpp
C:\Users\wolf\AppData\Local\Temp\cc6bIt03.o:main.cpp:(.text+0x15): undefined ref
erence to `DerClass::fn()'
collect2.exe: error: ld returned 1 exit status


Thank you.
Last edited on
<headername> is for(and should be) standard libraries, one that is common in nature with the compiler. You can try using "headername" for linked ones.

#include <iostream>

this should also be located in lib/DerClass since you are using std::cout in the definition of the class and NOT on the class declaration(the one in hpp).

Also note that it would be better to put them in the same directories so as to not have problems like these. But if you really want to, you can set your compiler to do that in your includes. For more info about how to do this, visit your IDE/compiler site and see how to 'link' them up(usually in this case, just search for how to include files in compiler name).
Hi rjvc,

I changed the #include to quotes and moved all files into the same directory as you suggested.
Also removed the std::cout from the function, so that is no longer an issue.
Still getting the same error though.

main.cpp
1
2
3
4
5
6
7
8
9
#include "DerClass.h"

int main()
{
	DerClass der1;

	der1.fn();		//undefined reference to `DerClass::fn()'
				//compiles when this line is commented
}


lDerClass.h
1
2
3
4
5
6
7
8
9
#ifndef DERCLASS_H
#define DERCLASS_H

class DerClass
{
	public:
		void fn();
};
#endif 


DerClass.cpp
1
2
3
#include "DerClass.h"

void DerClass::fn() { }


g++ command and error:
C:\Users\wolf\Documents\demo_MinGW\inherit>g++ -Wall main.cp
p
C:\Users\wolf\AppData\Local\Temp\ccKX706N.o:main.cpp:(.text+0x15): undefined ref
erence to `DerClass::fn()'
collect2.exe: error: ld returned 1 exit status



Last edited on
I think its your compiler. See to it that the compiler is properly set.Btw I'm using codeblocks and it works just fine. :)
Thanks ne555; that was it! I forgot to list all the cpp files.

This compiled:
C:\Users\wolf\Documents\demo_MinGW\inherit>g++ -Wall main.cpp DerClass.cpp
Topic archived. No new replies allowed.