0
votes

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.

1
That error tends to follow at least one (possibly more) other error from the linker. Those errors will usually be related to the cause of the problem. In this case, the problem is that the declaration of derivative2() immediately after the using namespace std does not match the definition, so you are overloading the function. The call of derivative2() in main() 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. - Peter
@Peter Which is the correct definition? When they are equal I get a bunch of errors saying that fun cannot be used as a function. - mattiav27
The "correct definition" depends on what you're trying to achieve. In terms of your code, the definition of derivative2() [which occurs after main()] is what you intend. That function accepts a (pointer to) a function as the first argument. However, the declaration of derivative2() after the using namespace std accepts a double as the first argument. The usage of derivative2() in main() also passes a double (the result of calling fun(x)) to derivative2() - consistent with the preceding declaration of derivative2() but NOT with the subsequent definition. - Peter

1 Answers

1
votes
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, 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.