【问题标题】:C++ include header not working [duplicate]C ++包含标头不起作用[重复]
【发布时间】:2013-07-10 11:38:27
【问题描述】:

我正在学习 C++ 的一些基本概念,但我一直在使用标头来使用多个文件。 我有 3 个文件。

计算器.h

#ifndef CALCULATOR_H_CAL
#define CALCULATOR_H_CAL
class Calculator{
        int a,b;
        public:
        Calculator();
        Calculator(int,int);
    int op();
};
#endif

计算器.cpp

#include<iostream>
#include "Calculator.h"

    Calculator::Calculator(){
        a=0;b=0;
    }
    Calculator::Calculator(int c,int d){
        a=c;b=d;    
    }
    int Calculator::op(){
        return a*b;
    }

Main.cpp

#include<iostream>
#include "Calculator.h"    

int main(){
    Calculator a(2,3);
    int b=a.op();
    std::cout << b;
}

但是用 g++ Main.cpp 编译会报错:

/tmp/cc09isjx.o: In function `main':
Main.cpp:(.text+0x83): undefined reference to `Calculator::Calculator(int, int)'
Main.cpp:(.text+0x8c): undefined reference to `Calculator::op()'
collect2: ld returned 1 exit status

这里有什么问题?

【问题讨论】:

  • 因为他找不到方法的实现。试试 g++ Main.cpp Calculator.cpp
  • 标题包含是一个编译问题,你没有问题。未定义的引用是一个链接问题,与标题完全无关。
  • 哦。我不知道,您需要指定所有文件名。谢谢。
  • 你需要指定链接部分的文件
  • 既然你刚刚开始学习 C++,那么现在你应该学习的一些东西是“编译单元”和“链接”的概念。关于这件事有大量的文档,所以我会让你研究一下。

标签: c++ compiler-errors g++


【解决方案1】:

你是如何编译代码的?我认为问题在于您在编译时没有将计算器文件与主文件链接。试试这个:

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

【讨论】:

    【解决方案2】:

    如果你没有用 main() 正确链接文件,那么你将无法正确编译它。

    试试这个-

    g++ main.cpp 计算器.cpp

    这应该包括你的头文件。

    【讨论】:

      【解决方案3】:

      可以使用命令编译:

      g++ Main.cpp Calculator.cpp
      

      【讨论】:

        猜你喜欢
        • 2016-11-20
        • 2011-10-23
        • 1970-01-01
        • 2012-09-16
        • 2011-12-04
        • 2010-09-30
        • 1970-01-01
        • 1970-01-01
        • 2012-09-22
        相关资源
        最近更新 更多