[LC++]How to link

Paul Carter carterp at acm.org
Wed Aug 29 00:02:03 UTC 2001


On Tue, Aug 28, 2001 at 03:12:45PM +0200, Laszlo Boszormenyi wrote:
> Hi!
> 
> I have these files, but I can not link them together. What I do:
> g++ -c My.cpp
> g++ -c caller.cpp
> g++ My.o caller.o -o caller
> 
> I get:
> caller.o: In function `main':
> caller.o(.text+0xe): undefined reference to `My::My(void)'
> caller.o(.text+0x6f): undefined reference to `My::~My(void)'
> caller.o(.text+0x9a): undefined reference to `My::~My(void)'
> collect2: ld returned 1 exit status
> 
> My g++ version is 2.95.4. Thanks in advance, Laszlo

> #include <iostream>
> 
> #include "My.h"
> 
> int main(void) {
> 	My my;
> 	cout << "Starts..." << endl;
> 	cout << "...ends" << endl;
> 	return 0;
> }

> #include <iostream>
> 
> class My {
> public:
> 	My(void) {
> 		cout << "Constructed" << endl;
> 	}
> 	~My(void) {
> 		cout << "Destructed" << endl;
> 	}
> };
The code above is the problem. By putting the code inside your class, you
are implicitly declaring them as inline. This means that no linkable functions
are created for them. You can either move the code to the header file or
declare the member functions outside of your class in your cpp file:

My::My() {
  cout << "Constructed" << endl;
}
My::~My(void) {
  cout << "Destructed" << endl;
}

The void's are not the problem. There are not needed, but there's no problem
putting them there either.


> #ifndef __MY_H
> #define __MY_H
> 
> class My {
> public:
> 	My(void);
> 	~My(void);
> };
> 
> #endif


-- 
Paul Carter [carterp at acm.org] [http://www.drpaulcarter.com/]



More information about the tuxCPProgramming mailing list