Reputation: 685
I am writing a simple program to calculate the derivative of a function, but I always 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 is not useful in my case.
Upvotes: 1
Views: 3410
Reputation: 136208
double derivative2(double (fun), double step, double x);
And
double derivative2(double fun(double), double step, double x)
Are different things. In the first declaration fun
is double
, and in the second fun
is double(*)(double)
(a pointer to a function).
Because this function calculates a derivative at a point, the right declaration is the one with the function pointer.
Fix:
double derivative2(double fun(double), double step, double x); // 'fun' is a function pointer.
// ...
cout << derivative2(fun, h, x) << endl; // Pass fun as a function pointer.
Upvotes: 3