I am writing a simple program to calculate the derivative of a function, but I alway get the error:
collect2: error: ld returned 1 exit status
Here is my program:
#include <iostream>
#include <stdlib.h>
#include <math.h>
using namespace std;
double derivative2(double (fun), double step, double x);
double fun(double);
int main(int argc, char* argv[]){
double h = atof(argv[1]);
double x = sqrt(2);
cout << derivative2(fun(x),h,x) << endl;
return 0;
}
double derivative2(double fun(double),double step, double x){
return ((fun(x+step)-fun(x))/step);}
double fun(double x){
return atan(x);
}
I have found this post, but it it not useful in my case.
derivative2()immediately after theusing namespace stddoes not match the definition, so you are overloading the function. The call ofderivative2()inmain()calls the one that is not defined. Since there is a call of a function that is not defined, the linker will typically report something like an "undefined reference". The collect2 error follows from that. - Peterderivative2()[which occurs aftermain()] is what you intend. That function accepts a (pointer to) a function as the first argument. However, the declaration ofderivative2()after theusing namespace stdaccepts adoubleas the first argument. The usage ofderivative2()inmain()also passes adouble(the result of callingfun(x)) toderivative2()- consistent with the preceding declaration ofderivative2()but NOT with the subsequent definition. - Peter