2

I am learning some basic concepts of C++ and I am stuck in using multiple files using headers. I have 3 files.

Calculator.h

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

Calculator.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;
}

But compiling with g++ Main.cpp gives errors:

/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

What is wrong here?

Abhishek
  • 2,543
  • 4
  • 34
  • 46
  • because he can't find the implementation of the methods. try g++ Main.cpp Calculator.cpp – Alexis Jul 10 '13 at 11:41
  • 1
    Header inclusion is a compilation matter, you have no problem with that. Undefined reference is a linking matter, totally unrelated to headers. – syam Jul 10 '13 at 11:43
  • Ohh. I dint know, you need to specify all the file names. Thanks. – Abhishek Jul 10 '13 at 11:43
  • you need to specify the files for the linking part – Alexis Jul 10 '13 at 11:44
  • Since you're just beginning to learn C++, some things you should learn right now are the notions of "compilation unit" and "linking". There is extensive documentation on that matter so I'll let you research it. – syam Jul 10 '13 at 11:46

3 Answers3

4

How are you compiling the code? I believe the issue is that you aren't linking the calculator files with the main when compiling. Try this:

g++ -c calculator.cpp
g++ main.cpp -o main calculator.o
Guillaume Rochat
  • 400
  • 2
  • 13
1

If you are not linking the the files with main() correctly, then you won't be able to compile it correctly.

try this-

g++ main.cpp Calculator.cpp

This should now include your header file.

0

You can use the command to comlile:

g++ Main.cpp Calculator.cpp
Charles
  • 175
  • 1
  • 8