1

I have the following code:

main.c

#include "checksum.h"

void main()
{
    char *Buf ="GPGGA204502.005106.9813N11402.2921W1090.91065.02M-16.27M";
    checksum(Buf);
}

checksum.c

#include <stdio.h>
#include <string.h>

checksum(char *Buff)
{
    int i;
    unsigned char XOR;
    unsigned long iLen = strlen(Buff);
    printf("Calculating checksum...\n");
    for (XOR = 0, i = 0; i < iLen; i++)
        XOR ^= (unsigned char)Buff[i];
    printf("%X \n",XOR);
}

checksum.h

#ifndef CHECKSUM_H_INCLUDED
#define CHECKSUM_H_INCLUDED

void checksum(char *Buff);

#endif

When compiling I get the following error:

/tmp/ccFQS7Ih.o: In function `main':
main.c:(.text+0x18): undefined reference to `checksum'
collect2: ld returned 1 exit status

I can't figure out what the problem is?

Daniel Sloof
  • 12,568
  • 14
  • 72
  • 106
StianL
  • 45
  • 1
  • 5
  • 2
    Can you post the compiler command? You need to link the `checksum.o` when building `main`. – hmjd Mar 20 '12 at 10:34
  • You have gotten a warning also when compiling (and if not, your compiler settings are bad). Your function declaration (that's what in the .h file) and its defintion (that what is in the .c) do not match. By not writing the `void` before checksum, the function is re-declared as a function returning an `int`. – Patrick Schlüter Mar 20 '12 at 12:09

3 Answers3

3

You are compiling only one file not both. More precisely, you are not linking the files together.

I don't know your compiler, but with gcc, it would be something like this:

gcc -c main.c          <-- compile only
gcc -c checksum.c      <-- compile only
gcc main.o checksum.o  <-- link the two

Edit: To automate this process, take a look at the make program which reads Makefiles.

Shahbaz
  • 46,337
  • 19
  • 116
  • 182
  • Hmm, that did the trick! Is there a way to automate this when using gcc? I't is for AVR, but I'm testing some code in linux terminal... – StianL Mar 20 '12 at 10:48
  • You can also do `gcc main.c checksum.c` – asaelr Mar 20 '12 at 11:55
  • @StianL, I tried explaining makes and Makefiles twice now, but my computer kept crashing for no apparent reason and I lost all I had written. Your bad luck. Anyway, follow the links I wrote in my edit and you should be able to conjure up a simple Makefile quite quickly. – Shahbaz Mar 20 '12 at 16:24
2

You could also try gcc -o program.out main.c checksum.c which will compile and link both files together

Dharma
  • 69
  • 5
1

I think: in checksum.c, you should include checksum.h.

Anthony
  • 12,177
  • 9
  • 69
  • 105
anhldbk
  • 4,559
  • 5
  • 29
  • 37
  • -1. That's a linker error, it doesn't occur during the compile stage, but during linkage. –  Mar 20 '12 at 10:50