【问题标题】:c++ error collect2: error: ld returned 1 exit statusc ++错误collect2:错误:ld返回1退出状态
【发布时间】:2017-10-12 12:36:17
【问题描述】:

我正在编写一个简单的程序来计算函数的导数,但我总是得到错误:

collect2: 错误:ld 返回 1 个退出状态

这是我的程序:

#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);
}

我找到了this 的帖子,但它对我来说没用。

【问题讨论】:

  • 该错误往往跟随链接器的至少一个(可能更多)其他错误。这些错误通常与问题的原因有关。在这种情况下,问题在于紧跟在using namespace std 之后的derivative2() 的声明与定义不匹配,因此您正在重载该函数。 main()derivative2()的调用调用了未定义的那个。由于调用了未定义的函数,链接器通常会报告类似“未定义引用”的内容。 collect2 错误随之而来。
  • @Peter 正确的定义是什么?当它们相等时,我会收到一堆错误,说 fun 不能用作函数
  • “正确定义”取决于您要达到的目标。就您的代码而言,derivative2() [出现在main() 之后] 的定义是您想要的。该函数接受一个(指向)函数作为第一个参数。但是,using namespace std 之后的 derivative2() 声明接受 double 作为第一个参数。在main() 中使用derivative2() 也会将double(调用fun(x) 的结果)传递给derivative2() - 与derivative2() 的前面声明一致,但与后续定义不一致。

标签: c++ compilation


【解决方案1】:
double derivative2(double (fun), double step, double x);

还有

double derivative2(double fun(double),double step, double x)

是不同的东西。在第一个声明中fundouble,在第二个fun 中是double(*)(double)(指向函数的指针)。

因为这个函数计算一个点的导数,所以正确的声明是带有函数指针的那个。

修复:

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.

【讨论】:

    猜你喜欢
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-19
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    相关资源
    最近更新 更多