C++ error: "undefined reference to cnt(int) collect2: error: ld returned 1 exit status [closed]

StackOverflow https://stackoverflow.com/questions/14411042

문제

When I compile this C program, I get an error:

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

collect2: error: ld returned 1 exit status

What does it mean? Here is the code:

#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;
}
도움이 되었습니까?

해결책

It means that it can not find a definition for int cnt(int);, which main() uses and you forward declare.

Instead, you define:

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

These are two different signatures. One takes an integer argument, and the other takes an array of integers.

Additionally, this statement is incorrect:

q=cnt(x[30]);

This takes the 31st element at index 30 from the x array. However, x is only declared to be of size 30. Since you are using x as an array inside your function, you probably just want to change your forward declaration to:

int cnt(int[30]);

And then invoke it like this:

q = cnt(x);

다른 팁

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

is not the same as:

int cnt(int x) { ... }

While you declare a prototype for the function taking a single integer, you never define such a function. Instead you define one taking an array.

You need to figure out whether you want to pass the array or an element of the array. The call:

q=cnt(x[30]);

attempts to pass the 31st element of the array (which doesn't exist by the way). I suspect (since you're dereferencing x in the function) you probably wanted to just pass x, which is the entire array (or, more correctly, the address of the first element of said array).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top