0

while reading the book c++ for mathematicians

i have to find gcd(greatest common divisor)

according to the book i make 3 files

gcd.h

#ifndef GCD_H
#define GCD_H

/**
* Calculate the greatest common divisor of two integers.
* Note: gcd(0,0) will return 0 and print an error message.
* @param a the first integer
* @param b the second integer
* @return the greatest common divisor of a and b.
*/
long gcd(long a, long b);


#endif

gcd.cc

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

using namespace std;

long gcd(long a, long b) {
    //if a and b are both zero, 
    //print an error and return0

    if ((a==0) && (b==0)) {
        cerr <<"warning: gcd got both arguments 1";
        return 0;

    }
    //a,b both are non negative
    if (a<0){
        a=-a;
    }
    if (b<0){
        b=-b;
    }

    //if a is zero the ans is b
    if (a==0) {
        return b;
    }

    //check the possibilites from 1 to a
    long d;
    for (long t=1; t<a; t++){
        if ((a%t==0) && (b%t==0)){
            d=t;
        }
        
    }
    return d;
}

and

gcd.cpp

#include "gcd.h"
#include <iostream>
#include<stdio.h>
#include <stdlib.h>


using namespace std;

int main(){
    long a,b;
    cout<< "enter the 1st no.: " << endl;
    cin>>a;
    cout<<"enter the 2nd number.: ";
    cin>>b;
    cout << " the gcd of " <<a<<" and "<<b<<" is "
    <<gcd(a,b);
    
    return 0;
}

but the error is coming

(.text+0x1b): undefined reference to `main'
collect2: error: ld returned 1 exit status

i'm not understanding the role of .cc file

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 1
    You need to compile and link both the .cc and the .cpp files. Terrible algorithm. Look up Euclid's. Terrible code too, as `d` is not initialized. – user207421 Mar 02 '22 at 03:52
  • C and C++ are different languages. Why do you tag C here? – phuclv Mar 02 '22 at 03:54
  • If you are using VSCode remember that by default it is setup to build only the active file into your executable. The official documentation tells you about the change you need to make to tasks.json to change that default behavior. – drescherjm Mar 02 '22 at 04:20

1 Answers1

0

First note that the program compiles and links successfully here. You need to compile all the source files(.cc and .cpp in your given example). Then you need to link the resultant object files.

i'm not understanding the role of .cc file

gcd.cc file provides the implementation/definition of the function gcd. This file is a source file.

gcd.h file provides the declaration of the function gcd. This file is a header file.

gcd.cpp file is where the main() function(the entry point) is defined. This file is also a source file.

If you're using gcc, the command you would use to built your program would be:

g++ gcd.cc gcd.cpp -o program

The above command will generate a binary named program. You can execute that binary using ./program in the terminal.

Jason
  • 36,170
  • 5
  • 26
  • 60