I'm trying to create a Makefile to compile my project. However, when I use the 'math.h' library, my make fails. This is the Makefile file :

run: tema1

build: tema1.c
        gcc tema1.c -o tema1 -lm

        rm *.o tema1

The part of the code where I use the pow() and sqrt() is :

float score = sqrt(k) + pow(1.25, completed_lines);

But, even compiling using '-lm', I still get this error :

> /tmp/ccSQVWNy.o: In function `easy_win_score': tema1.c:(.text+0x1518):
> undefined reference to `sqrt' tema1.c:(.text+0x1540): undefined
> reference to `pow' collect2: error: ld returned 1 exit status
> <builtin>: recipe for target 'tema1' failed make: *** [tema1] Error 1

Any idea why and how can I fix this ? If I only use this in the terminal :

gcc tema1.c -o tema1 -lm

it works, but in the Makefile, it fails.


This happens because your Makefile doesn’t explain how to build tema1 (from Make’s perspective), so it uses its built-in rules:

  • run depends on tema1;
  • tema1 doesn’t have a definition, but there’s a C file, so Make tries to compile it using its default rule, which doesn’t specify -lm.

To fix this, say

tema1: tema1.c
        gcc tema1.c -o tema1 -lm

instead of build: tema1.c etc.

You can reduce repetition by using automatic variables:

tema1: tema1.c
        gcc $^ -o $@ -lm

To keep “named” rules (run, build etc.), make them depend on concrete artifacts (apart from clean, since it doesn’t produce anything), add separate rules for the concrete artifacts, and mark the “named” rules as phony (so Make won’t expect a corresponding on-disk artifact):

build: tema1

tema1: tema1.c
        gcc $^ -o $@ -lm

.PHONY: run build clean

It’s also worth changing clean so it doesn’t fail when there’s nothing to clean:

        rm -f *.o tema1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.