Search code examples
c++undefined-referenceexitstatus

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


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

Solution

  • 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);