创建静态库时makefile中未定义的引用错误

时间:2010-10-15 21:43:12

标签: c linux makefile static-libraries

我有4个.c文件hello.chere.cbye.cmain.c。 一个头文件mylib.h

内容如下

的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

用于创建静态库的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 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

问题:当我执行命令

make -f Makefile all 

我收到错误:     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

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

2 个答案:

答案 0 :(得分:2)

这实际上对我有用。尝试rm mylib.a,然后make

答案 1 :(得分:0)

这对我来说很有问题,你没有指定“全部”目标:

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$