c - 创建静态库时生成文件中的 undefined reference 错误

标签 c linux makefile static-libraries

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

内容如下

你好.c

#include<stdio.h>

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

这里.c

#include<stdio.h>

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

再见

#include<stdio.h>

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

主程序

#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

问题:我该如何解决这个问题?为什么会有 undefined reference

最佳答案

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

关于c - 创建静态库时生成文件中的 undefined reference 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3946376/

相关文章:

c - autoconf:检查成员的偏移量

c++ - 调用宏时参数太多

c - 带有依赖于操作系统的编译器的 makefile

windows - 在 Windows 上的 Makefile 中使用环境变量

已安装 python-dev 和 Python.h,但包含错误

c - 在C中以特定格式打印出二维数组

linux - 通过 `creact-react-app` react 应用程序不工作

c - 多线程程序中不接收UDP并输出数据

c - Linux C 数组长度问题

c++ - 未正确考虑 Makefile 中的依赖项