Error: collect2: ld returned 1 exit status ?

Hello!
I'm just practicing using classes in separate files. My output should be "I am a banana!", but instead I get nothing when I run my compiled code.
I'm really not sure what I'm doing incorrectly. (All three files are in the same directory) Any input would be much appreciated.

main.cpp:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include "Apple.h"

using namespace std;

int main(){

	Apple appleObject;
	return 0;

}



Apple.h:
1
2
3
4
5
6
7
8
9
10
11
#ifndef APPLE_H
#define APPLE_H

class Apple{

	public:
		void Banana();

};

#endif 



Apple.cpp:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include "Apple.h"

using namespace std;

Apple::Banana(){

	cout << "I am a banana!\n";

}
Last edited on
Well you created the object but you never called the function(method).

Before returning in the main function try adding: appleObject.Banna();

Also the return type should be void on line 6 in the apple.cpp file
Last edited on
Oh, I assumed that the Banana function would automatically run because Apple::Banana was a constructor for the class, so when I created the appleObject, it would run Banana.

I added appleObject.Banana(); to the main function and then I added void in front of Apple::Banana and I got the error:

main.cpp(.text+0x11): undefined reference to 'Apple::Banana()'
collect2: ld returned 1 exit status
That's not a constructor.

A constructor would need the same name as the object anyways.

1
2
3
4
5
6
7
8
9
10
class Apple
{
    public:
        Apple(void); //constructor
};

Apple::Apple(void) //constructor
{
    std::cout << "I am a banana?" << std::endl;
}
Oh! That makes a lot more sense.

Alright, I changed my code knowing this, but now I'm getting an error saying "invalid use of Apple::Apple".
Can I see the code?
Sure!

main.cpp:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include "Apple.h"

using namespace std;

int main(){

	Apple appleObject;
	
	return 0;
}



Apple.h:
1
2
3
4
5
6
7
8
9
10
11
#ifndef APPLE_H
#define APPLE_H

class Apple{

	public:
		Apple(void);

};

#endif 



Apple.cpp:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include "Apple.h"

using namespace std;

Apple::Apple(void){

	cout << "I am a banana!\n";

}




The error I get is:

/tmp/ccC63aaO.o: In function `main':
main.cpp:(.text+0x11): undefined reference to `Apple::Apple()'
collect2: ld returned 1 exit status
I would try doing a clean build, you shouldn't be getting that error.

Ah, I figured out that my errorwas in my method of compiling.
I forgot to compile Apple.cpp along with main.cpp.

When I used: gcc Apple.cpp main.cpp -o test -lstdc++
it worked perfectly.


Thanks for your help! Especially with straightening out constructors. Much appreciated.
Thanks! :D
Topic archived. No new replies allowed.