简体   繁体   中英

Problem separating .h and .cpp file

I am writing a class and need to separate the declarations from the implementation, but I keep receiving "undefined reference" errors when compiling and linking my test program. It works fine when I include the implementation in the .h file, so I believe I am doing something wrong in there. I just can't figure out what.

Huge_Integer.h

#ifndef HUGE_INTEGER_H
#define HUGE_INTEGER_H

#include <vector>
#include <string>

using namespace std;

class Huge_Integer
{
   public:
      Huge_Integer();
      Huge_Integer(string);
      void input();
      string output();
      void add(Huge_Integer);
      void subtract(Huge_Integer);
      bool is_equal_to(Huge_Integer);
      bool is_not_equal_to(Huge_Integer);
      bool is_greater_than(Huge_Integer);
      bool is_less_than(Huge_Integer);
      bool is_greater_than_or_equal_to(Huge_Integer);
      bool is_less_than_or_equal_to(Huge_Integer);
   private:
      vector<int> value;
};

#endif

Huge_Integer.cpp

#include<vector>
#include<string>
#include<iostream>

#include "Huge_Integer.h"

using namespace std;

// all stubs for now...

Huge_Integer::Huge_Integer()
{
   cout << "object created\n";
}

Huge_Integer::Huge_Integer(string s)
{
   cout << "object created\n";
}

//etc...

It also works if I put #include "Huge_Integer.cpp" in my test file, but I shouldn't have to do that, right?

I am using MinGW.

Thanks in advance!

Edit: Added stubs from my .cpp file

Sounds like a linking issue. What that means is that you have to compile your class first -- this will create a compiled object file. Then compile the main program while passing in this compiled version of the class.

Like this:

g++ -c huge_integer.cpp
g++ main.cpp huge_integer.o

Substitute your mingw command for g++ if it is different.

Not related to linking, but you are referring to Huge_Integer inside the class declaration itself.

At least with g++, you should add a forward declaration before so that Huge_Integer has meaning inside the class declaration thus:

class Huge_Integer;   // forward declaration

class Huge_Integer {
  Huge_Integer();
  // etc...
  void add(Huge_Integer);

Note: I don´t have comment privileges, so I had to type in the answer box.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM