[c] C compiling - "undefined reference to"?

I am making a reliable data transfer protocol and have the function prototype

void tolayer5(int, char data[]);

With the structs

struct msg {
  char data[20];
};

struct pkt {
   int seqnum;
   int acknum;
   int checksum;
   char payload[20];
};

And when I call the function in this format:

tolayer5(A, packet.payload);

Where A is an int and packet.payload is a struct pkt, I get the error "undefined reference to 'tolayer5(int, char*)'. Can you help me see what I'm missing here?

void tolayer5(int AorB, char data[])
{
  int i;
  if (TRACE>2)
  {
     printf("TOLAYER5: data received:");
     for (i=0; i<20; i++)
        printf("%c",data[i]);
     printf("\n");
  }
}

Thank you all for helping with the original issue! :) When trying to fix that one, however, I ran into an infinite loop that I think has something to do with me addressing characters in an array incorrectly (it's been awhile since I've done C like this. Can you help me to find where I'm creating an infinite loop?

I have updated the above code to what I'm now working with. Notice the main changes have been to my function:

void tolayer5(int AorB, char data[])

And this line inside the function: printf("%c",msgReceived.data[i]); since now it's just:

printf("%c",data[i]);

This question is related to c data-structures

The answer is


As stated by a few others, this is a linking error. The section of code where this function is being called doesn't know what this function is. It either needs to be declared in a header file an defined in its own source file, or defined or declared in the same source file, above where it's being called.

Edit: In older versions of C, C89/C90, function declarations weren't actually required. So, you could just add the definition anywhere in the file in which you're using the function, even after the call and the compiler would infer the declaration. For example,

int main()
{
  int a = func();
}

int func()
{
   return 1;
}

However, this isn't good practice today and most languages, C++ for example, won't allow it. One way to get away with defining the function in the same source file in which you're using it, is to declare it at the beginning of the file. So, the previous example would look like this instead.

int func();

int main()
{
   int a = func();
}

int func()
{
  return 1;
}

Make sure your declare the tolayer5 function as a prototype, or define the full function definition, earlier in the file where you use it.