【问题标题】:Makefile for creating a library in Linux doesn't compile用于在 Linux 中创建库的 Makefile 无法编译
【发布时间】:2012-07-21 01:12:04
【问题描述】:

我有 3 个文件,my_pipe.hmy_pipe.cmain.c,其中 my_pipe 应该是一个库。

当我在 Eclipse 中编译它时,它编译得很好,没有错误,但是当我在 terminal 中运行以下 makefile 并点击 make 时:

exer3:  main.o libmywrapper.a

    gcc main.c libmywrapper.a -o exer3 -static -lrt



libmywrapper.a: my_pipe.o

    ar rcs libmywrapper.a my_pipe.o



main.o: main.c my_pipe.h

    gcc -lpthread -lrt -c main.c



my_pipe.o:  my_pipe.c my_pipe.h

    gcc -lpthread -lrt -c my_pipe.c

我明白了:

a@ubuntu:~/Desktop/myExer$ make
gcc -lpthread -lrt -c main.c
gcc -lpthread -lrt -c my_pipe.c
ar rcs libmywrapper.a my_pipe.o
gcc main.c libmywrapper.a -o exer3 -static -lrt
libmywrapper.a(my_pipe.o): In function `shm_pipe_init':
my_pipe.c:(.text+0x61): undefined reference to `sem_init'
libmywrapper.a(my_pipe.o): In function `shm_pipe_read':
my_pipe.c:(.text+0x17f): undefined reference to `sem_wait'
my_pipe.c:(.text+0x196): undefined reference to `sem_getvalue'
my_pipe.c:(.text+0x1ba): undefined reference to `sem_wait'
libmywrapper.a(my_pipe.o): In function `shm_pipe_write':
my_pipe.c:(.text+0x4b7): undefined reference to `sem_post'
collect2: ld returned 1 exit status
make: *** [exer3] Error 1

知道 makefile 有什么问题吗?

谢谢

已更新,以上!

【问题讨论】:

  • 看起来其他目标尚未构建,或者这只是重新运行?
  • @lynxlynxlynx:什么都没建。
  • 你试过把 -lpthread 放在命令行的最后吗?我发现订单是相关的。另外,我知道您可能只需要 -lpthread 而不需要 -lrt?
  • 能否请您删除所有目标文件,包括库,然后重新制作。拥有完整的构建输出可能会有所帮助
  • @lserni:当我在 eclipse 中编译时,它需要两个 .此外,我尝试将 -lpthread 放在末尾,结果与它显示的结果相同。

标签: c linux eclipse ubuntu makefile


【解决方案1】:

诸如-lpthread-lrt 之类的链接器选项必须放在编译行的最后。试试:

gcc main.o libmywrapper.a -o exer3 -static -lrt

编译时,您不需要链接器标志。例如:

main.o: main.c my_pipe.h
  gcc -c main.c

【讨论】:

  • 顺便说一句:链接步骤中应该是main.o,而不是main.c
【解决方案2】:

解决办法如下:

exer3:  main.o sharedMemoryLib.a

    gcc main.o sharedMemoryLib.a -o exer3 -static -lrt -lpthread



sharedMemoryLib.a:  my_pipe.o

    ar rcs sharedMemoryLib.a my_pipe.o



main.o: main.c my_pipe.h

    gcc -c main.c



my_pipe.o:  my_pipe.c my_pipe.h

    gcc -c my_pipe.c

【讨论】:

  • 编译时不需要链接器标志,链接时应使用新编译的main.o
  • 编译器的最后一行可以读成:gcc -c main.c-lpthread -lrt 仅在链接时才需要。
  • 你(=Ron,问题的原始发帖人)真的应该了解更多关于 GNU make 以及它使用的许多隐式规则和变量,例如 CFLAGS
  • 运行make -p 了解make 知道的所有规则(和变量)......然后阅读文档
  • 我觉得不错。当然,你可以用 makefile 做很多魔法。例如。编译时输入gcc -c $<。但这也是消磨时间的好方法;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多