1

I'm trying to follow the tutorial here:

http://cocoadevcentral.com/articles/000081.php

And soon as I reached the "Header files" section, I kept getting a strange error message after running gcc test1.c -o test1 in the Mac OSX command line:

Undefined symbols for architecture x86_64:
  "_sum", referenced from:
      _main in ccdZyc82.o
  "_average", referenced from:
      _main in ccdZyc82.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

math_functions.h:

int sum(int x, int y);
float average(float x, float y, float z);

math_functions.c:

int sum(int x, int y) {
  return x + y;
}

float average(float x, float y, float z) {
  return (x + y + z)/3;
}

And finally, my test1.c:

#include <stdio.h>
#include "math_functions.h"

main() {
  int thesum = sum(1, 2);
  float ave = average(1.1, 2.21, 55.32);

  printf("sum = %i\nave = %f\n(int)ave = %i\n", thesum, ave, (int)ave);
}

I seem to have followed everything correctly and I don't understand where that error is coming from. Help?

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
Matthew Quiros
  • 13,385
  • 12
  • 87
  • 132
  • http://stackoverflow.com/questions/1754460/apples-gcc-whats-the-difference-between-arch-i386-and-m32 Hope this helps. – AechoLiu Jul 16 '12 at 09:14

2 Answers2

2

You have two separate source files, math_functions.c and test1.c, they both need to be compiled, and linked together. The error messages tells you that the compiler doesn't find the functions average and float and that is because they come from math_functions.c and you only compiled test1.c.

The example you linked to tells you to type:

gcc test3.c math_functions.c -o test3
Guillaume
  • 4,331
  • 2
  • 28
  • 31
1

You are not linking in the object file that contain the sum() and average() functions.

Do this:

$ gcc -c -o math_functions.o math_functions.c
$ gcc -c -o test1.o test1.c
$ gcc -o test1 test1.o math_functions.o

The first two lines compile the source files into object files and the final line links the object files into the executable file.

You need to invest some time learning make, as no developer can be bother to type that much just to compile (also before you know it you've got the filenames wrong and compiled over your source file!).

trojanfoe
  • 120,358
  • 21
  • 212
  • 242