tags:

views:

70

answers:

3

I already know the differences between a header file and a library. However, when I'm writing my makefile, I have some difficulties on deciding if I should put something as a dependency of the file or just at the linking rule.

For example: I have 2 simple files: main.c:

#include <stdio.h>
main(){
  printf("this is the sine or 90");
  sinus(90);
}

and func.c:

#include <math.h>
sinus(int num){
  return sin(num);
}

and my makefile is:

main:   main.o  func.o
    gcc main.o func.o -lm -o main

func.o: func.c
main.o: main.c

Well, my question is why this makefile works and this one doesn't:

main:   main.o  func.o
    gcc main.o func.o -lm -o main

func.o: func.c math.h
main.o: main.c
+2  A: 

You don't need to make func.o depend on math.h as that file is very unlikely to change.

Regarding the error you get if you do is because you don't explicitly specify how make should compile the file so it tries to deduce how to compile it and it only works in simple cases. I'm not sure exactly how make does it but I think it just does gcc -o target.o -c <your deps>.

cjg
+2  A: 

Because make is looking for a file "math.h" in the current directory and trying to do cc func.c math.h to produce func.o

cthom06
Not entirely right. It tries to find a rule that produces math.h. Since none exist the dependency will fail.
harald
A: 

Problem is that you don't know exactly how Makefile is resolved after using implicit rules - definitely there's one which causes problems you have. (maybe try to compile math.h, or math.h is not found etc.. (you didn't posted errors you have so we can only speculate).

I would advice you to disable implicit rules by calling make with "-r" and do everything explicitly - this way you will learn more as you'll know how makefile works instead of knowing how to write makefiles which works under some circumstances.

More on implicit rules: Make documentation - Implicit rules

More on make Make documentation

XAder