【问题标题】:C++ error: "undefined reference to cnt(int) collect2: error: ld returned 1 exit status [closed]C ++错误:“对cnt(int)collect2的未定义引用:错误:ld返回1退出状态[关闭]
【发布时间】:2013-01-19 04:17:34
【问题描述】:

当我编译这个 C 程序时,我得到一个错误:

In function `main': maxcount.cpp:(.text+0x63): undefined reference to `cnt(int)'

collect2: error: ld returned 1 exit status

这是什么意思?代码如下:

#include<iostream>
using namespace std;
int cnt(int);
int main()
{
  int x[30],i,j,q;
  cout<<"enter x[i]";
  for(i=0;i<7;i++)
  {
    cin>>x[i];
  }
  q = cnt(x[30]);
}
int cnt(int x[30])
{
  int i,j;
  int max=x[0];
  int count=0;
  for(i=0;i<7;i++)
  {
    if(x[i]>max)
    {
      max=x[i];
    }
    else
    {
      max=x[0];
    }
  }
  for(i=0;i<7;i++)
  {
    if(max==x[i])
    {
      count++;
    }
  }
  cout<<count;
  return 0;
}

【问题讨论】:

  • 您普遍错误地使用了数组。看起来您认为数组的名称是 x[30],但事实并非如此;它的名字是x

标签: c++ undefined-reference exitstatus


【解决方案1】:

这意味着它找不到int cnt(int); 的定义,main() 使用并转发声明。

相反,您定义:

int cnt(int x[30]) { ... }

这是两个不同的签名。一个接受整数参数,另一个接受整数数组。

另外,这个说法是不正确的:

q=cnt(x[30]);

这会从x 数组中获取索引 30 处的 31st 元素。但是,x 仅声明为大小 30。由于您在函数中使用 x 作为数组,您可能只想将前向声明更改为:

int cnt(int[30]);

然后像这样调用它:

q = cnt(x);

【讨论】:

  • 谢谢你..它解决了我的问题
【解决方案2】:
int cnt(int x[30]) { ... }

等同于:

int cnt(int x) { ... }

虽然您声明一个采用单个整数的函数的原型,但您从未定义这样的函数。相反,您定义一个采用数组。

您需要弄清楚是要传递数组还是数组的元素。来电:

q=cnt(x[30]);

尝试传递数组的第 31 个元素(顺便说一句,它不存在)。我怀疑(因为你在函数中取消引用x)你可能只想传递x,这是整个数组(或者,更准确地说,是所述数组的第一个元素的地址)。

【讨论】:

  • 谢谢..它解决了我的问题
猜你喜欢
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-01
  • 2014-09-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多