-1

I already searched and found a solution for this problem but i find this a little bit strange. Anyway my problem is this:

Personal.h

class Personal
{
  public:
   Personal();
   int money;
    ~Personal();

  }

Personal.cpp

#include "Personal.h"
Personal::Personal()
{
 money = 1800;
}

Personal::~Personal(){};

Now i want to compile in main

main.cpp

#include "Personal.h"
#include <iostream>
#include <vector>

int main()
{
 std::vector<Personal> test(100);

 }

When I write: g++ -Wall main.cpp -o main it gives me :

undefine reference to Personal::Personal()
undefine reference to Personal::~Personal()

The solution:

g++ -Wall Personal.cpp main.cpp -o main

Why do i need compile the Personal.cpp too?

Or the other main version is to include instead of "Personal.h", "Personal.cpp"

main.cpp

#include "Personal.cpp"
#include <iostream>
#include <vector>

Then the normal g++ -Wall main.cpp -o main works

Can someone help me?

  • Why? Because that's how C++ works. If you think about it you are compiling personal.cpp in both cases. In the first case because you put it on the command line and in the second case because you included it in a file that you put on the command line. Either way it's getting compiled. – john Feb 28 '18 at 16:10
  • 1
    What makes you think that you don't need to compile `Personal.cpp`? – Jabberwocky Feb 28 '18 at 16:12
  • Possible duplicate of [How does the compilation/linking process work?](https://stackoverflow.com/questions/6264249/how-does-the-compilation-linking-process-work) – UKMonkey Feb 28 '18 at 16:23
  • thank you i understand my problem now! – Newuser1234567 Feb 28 '18 at 16:26

1 Answers1

0

Why do i need compile the Personal.cpp too?

Because you use functions that are defined in that file. In particular, you use the functions Personal::Personal and Personal::~Personal.

Can someone help me?

Make sure that all functions (that are odr-used) are defined in exactly one (or in all files, in case of inline functions) of the source files that you compile and link together.

eerorika
  • 232,697
  • 12
  • 197
  • 326