在Linux中创建库的Makefile无法编译

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

在Eclipse中编译时,可以顺利编译通过,没有错误,但是当我在终端中运行以下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

I get this :

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
@lynxlynxlynx:没有任何东西被构建。 - JAN
你尝试过在命令行中最后放置“-lpthread”吗?我发现顺序很重要。另外,我理解你可能只需要“-lpthread”,而不是“-lrt”? - LSerni
@lserni:当我在Eclipse中编译时,它要求两个文件。此外,我尝试将“-lpthread”放在末尾,但结果相同。 - JAN
先尝试构建所有其他对象,然后我不确定这个隐式的“全部”目标是否有效,因为它会立即尝试构建exer3,而不考虑依赖关系。 - lynxlynxlynx
显示剩余2条评论
2个回答

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

最后编译步骤的行只需写成:gcc -c main.c。当链接时,-lpthread -lrt是必需的。 - steffen
1
运行 make -p 命令可以了解 make 知道的所有规则(和变量)...然后阅读文档。 - Basile Starynkevitch
请问您能否指点我一个好的makefile教程!!!我一直想学习C语言,所以最近开始尝试编写代码,但是就是找不到一个好的与makefile相关的教程。如果您能指点我一下,我将非常感激 :-) - nIcE cOw
@nIcE cOw: 这个帮了我很多:http://www.cs.swarthmore.edu/~newhall/unixhelp/howto_makefiles.html - JAN
@ron:谢谢您提供的链接 :-) 我会立即查看,我对C语言还很陌生,所以无法发表太多意见,希望您能在需要时给予帮助 :-) - nIcE cOw
显示剩余3条评论

2
链接器选项(如-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 - steffen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接