2

I'm struggling with compiling multiple files into a common program. I'm getting an error:

undefined reference to 'pi'

Here's the skeleton of my code and Makefile. What am I doing wrong? Thanks!

File: calcPi.c

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

#include "pi.h"

int main(int argc, char* argv[]) {
    long iterations = 1000000;
    int policy = 2;
    int numChildren = 3;
    pi(iterations, policy, numChildren);
    return 0;
}

File: pi.h

void pi(long iterations, int policy, int numChildren);

File: pi.c

#include "pi.h"

void pi(long iterations, int policy, int numChildren) {
    //lots of code here
}

I'm compiling this using a Makefile:

CC = gcc
CFLAGS = -c -g -Wall -Wextra
LFLAGS = -g -Wall -Wextra

all: calcPi pi

calcPi: calcPi.o
    $(CC) $(LFLAGS) $^ -o $@ -lm

pi: pi.o
    $(CC) $(LFLAGS) $^ -o $@ -lm

calcPi.o: calcPi.c
    $(CC) $(CFLAGS) $<

pi.o: pi.c
    $(CC) $(CFLAGS) $<

clean:
    rm -f pi calcPi
    rm -f *.o
    rm -f *~

EDIT: In response to the request for the entire error message:

In function 'main'" calcPi.c:55: undefined reference to 'pi' collect2: error: ld returned 1 exit status make: * [calcPi.o] error 1

4
  • 1
    Please edit your question to include the complete console output from your build process (especially the line where things are being linked). Commented Mar 12, 2013 at 19:20
  • Your CFLAGS should not contain -c IIRC. and you probably want to link all your object files calcPi.o and pi.o together (unless you have two different main-s in them...) Commented Mar 12, 2013 at 19:20
  • @BasileStarynkevitch: I'd think -c would be appropriate if you want to separate the compilation and linking phases, which appears to be the case here. Commented Mar 12, 2013 at 19:24
  • Run make -p; it will shows you the default COMPILE.c and the rule using it Commented Mar 12, 2013 at 19:26

1 Answer 1

3

First of all, is pi really supposed to be a separate application?

You're referring the pi() function from calcPi, but it's only been compiled into pi.o, so you need to add it as a dependency.

What I think you want to do, is to create calcPi using the calcPi.o and pi.o object files.

CC = gcc
CFLAGS = -c -g -Wall -Wextra
LFLAGS = -g -Wall -Wextra

all: calcPi

calcPi: calcPi.o pi.o
    $(CC) $(LFLAGS) $^ -o $@ -lm

calcPi.o: calcPi.c
    $(CC) $(CFLAGS) $<

pi.o: pi.c
    $(CC) $(CFLAGS) $<

clean:
    rm -f calc
    rm -f *.o
    rm -f *~
Sign up to request clarification or add additional context in comments.

2 Comments

Might want to remove pi from all as well.
That's it. Thanks! That helps me to understand this process a bit better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.