简体   繁体   English

分离.h和.cpp文件时出现问题

[英]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. 当我将实现包含在.h文件中时,它工作正常,因此我相信我在其中做错了什么。 I just can't figure out what. 我只是不知道是什么。

Huge_Integer.h 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 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? 如果将#include "Huge_Integer.cpp"放在测试文件中,它也可以工作,但我不必这样做,对吗?

I am using MinGW. 我正在使用MinGW。

Thanks in advance! 提前致谢!

Edit: Added stubs from my .cpp file 编辑:从我的.cpp文件添加了存根

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. 如果不同,请用mingw命令替换g ++。

Not related to linking, but you are referring to Huge_Integer inside the class declaration itself. 与链接无关,但是您是在类声明本身中引用Huge_Integer

At least with g++, you should add a forward declaration before so that Huge_Integer has meaning inside the class declaration thus: 至少对于g ++,应该在前面添加一个前向声明,以便Huge_Integer在类声明中具有含义,因此:

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. 注意:我没有评论权限,因此必须在答案框中输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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