[LC++]How to link

Chris Vine chris at cvine.freeserve.co.uk
Sun Sep 2 00:38:19 UTC 2001


On Tuesday 28 August 2001 14:12, 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

Hi,

The fact that you appended the (short) files to your e-mail rather than paste 
them in, coupled with a syntax error in My.cpp which made it look like a 
header file, meant that many of those who replied did not completely explain 
your error.  It would help if you put your code in a more user friendly form 
next time.

My.cpp contains the incorrect code and consisted of --

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

My.h is ok as far as it goes, and consisted of --

***
#ifndef __MY_H
#define __MY_H

class My {
public:
	My(void);
	~My(void);
};

#endif
***


caller.ccp consisted of --

***
#include <iostream>

#include "My.h"

int main(void) {
	My my;
	cout << "Starts..." << endl;
	cout << "...ends" << endl;
	return 0;
}
***

You tried to define the class methods specified in My.h in your file My.cpp, 
but did so incorrectly by attempting to redefine the class with inline 
methods.  You should have defined the class methods in My.cpp as follows --

#include "My.h"

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

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

Alternatively, as My.cpp contains a class definition with inline methods, you 
could have used that definition in My.h and have done without My.cpp 
entirely.  In other words, your file My.h could read --

#ifndef MY_H
#define MY_H

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

#endif

Note that you should not provide your own #defines prepended by __.  Those 
are reserved for the system.

Chris.



More information about the tuxCPProgramming mailing list