undefined reference to function

Why does the following code get link error "undefined reference to" function?
I copied the lines into a single file and it worked.
So maybe there is something wrong with the #includes, but I don't see what is wrong.
Please take a look.

Thank you.

main.cpp
1
2
3
4
5
6
7
8
9
10
11
#include "Child1.h"
#include "Child2.h"

int main()
{
	Child1 c1;
	Child2 c2;

	c1.fc();
	c2.fc();
}


A.h
1
2
3
4
5
6
7
#ifndef A_h
#define A_h

class A
{
};
#endif 


A.cpp
1
2
#include "A.h"
// no other code here 


Child1.h
1
2
3
4
5
6
7
8
9
10
11
#ifndef Child1_h
#define Child1_h
#include <iostream>
#include "A.cpp"

class Child1: public A
{
	public:
		void fc();
};
#endif 


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

void Child1::fc() { std::cout << "Child1 "; }


Child2.h
1
2
3
4
5
6
7
8
9
10
11
#ifndef Child2_h
#define Child2_h
#include <iostream>
#include "A.cpp"

class Child2: public A
{
	public:
		void fc();
};
#endif 


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

void Child2::fc() { std::cout << "Child2 "; }


link error:
C:\demo_MinGW\link_composite2>g++ main.cpp

C:\Users\wolf\AppData\Local\Temp\ccSNvt8X.o:main.cpp:(.text+0x15): undefined ref
erence to `Child1::fc()'
C:\Users\wolf\AppData\Local\Temp\ccSNvt8X.o:main.cpp:(.text+0x20): undefined ref
erence to `Child2::fc()'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: C:\Users\w
olf\AppData\Local\Temp\ccSNvt8X.o: bad reloc address 0x0 in section `.ctors'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: final link
 failed: Invalid operation
collect2.exe: error: ld returned 1 exit status
You need to compile all the source (cpp) files and link them together. Try:
g++ A.cpp Child1.cpp Child2.cpp main.cpp
Last edited on
Thanks Zhuge, that did the trick.
Topic archived. No new replies allowed.