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
CodePudding user response:
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.
CodePudding user response:
The .cc file is a source file. All source files in your code are first compiled into .o object files. The object files are then linked into your final executable. For more information, see this question