开发者

Undefined reference error in a makefile while creating static library

I have 4 .c files hello.c,here.c,bye.c and main.c. One header file mylib.h

The contents are as follows

hello.c

#include<stdio.h>

void hello()
{
    printf("Hello!\n");
}

here.c

#include<stdio.h>

void here()
{
     printf("I am here \n");
}

bye.c

#include<stdio.h>

void bye()
{
    printf("Bye,Bye");
}

main.c

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

int main()
{ 

  hello();
  here();
  bye();
  return 1;
}

mylib.h

#ifndef _mylib_
#define _mylib_

void hello();
void here();
void bye();

#endif

The makefile for creating a static lib is : Makefile

all:    myapp

#Macros

#Which Compiler
CC = gcc

#Where to install
INSTDIR = /usr/local/bin

#Where are include files kept
INCLUDE = .

#Options for developement
CFLAGS = -g -Wall -ansi

#Options开发者_如何学Go for release
#CFLAGS = -O -Wall -ansi

#Local Libraries
MYLIB = mylib.a

myapp:  main.o $(MYLIB)
        $(CC) -o myapp main.o $(MYLIB)

$(MYLIB):       hello.o here.o bye.o
                ar rcs $@ $^

main.o:         main.c mylib.h
hello.o:        hello.c
here.o:         here.c
bye.o:          bye.c

clean:
    -rm main.o hello.o here.o bye.o $(MYLIB)

install:        myapp
    @if [ -d $(INSTDIR) ]; \
    then \
            cp myapp $(INSTDIR);\
            chmod a+x $(INSTDIR)/myapp;\
            chmod og-w $(INSTDIR)/myapp;\
            echo "Installed in $(INSTDIR)";\
    else \
            echo "Sorry, $(INSTDIR) does not exist";\
    fi

Problem: When I execute the command

make -f Makefile all 

I get the error: gcc -o myapp main.o mylib.a

main.o: In function `main':

/home/usr/molly/main.c:7: undefined reference to `hello()'

/home/usr/molly/main.c:8: undefined reference to `here()'

/home/usr/molly/main.c:9: undefined reference to `bye()'

main.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0'

collect2: ld returned 1 exit status

make: *** [myapp] Error 1

Questions : How do I resolve this? Why is there an undefined reference


This actually works for me. Try rm mylib.a and then make


This works for me with the caveot that you are not specifying an 'all' target:

xxxx@xxxx-desktop:~/Desktop$ make -f Makefile
cc -g -Wall -ansi   -c -o main.o main.c
cc -g -Wall -ansi   -c -o hello.o hello.c
cc -g -Wall -ansi   -c -o here.o here.c
cc -g -Wall -ansi   -c -o bye.o bye.c
ar rcs mylib.a hello.o here.o bye.o
cc -o myapp main.o mylib.a
xxxx@xxxx-desktop:~/Desktop$ ./myapp 
Hello!
I am here 
Bye,Byexxxx@xxxx-desktop:~/Desktop$ 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜