尽管我在代码中包含了“#include”,但当我使用内置的 qsort 函数时,clang 给出了错误:
schedule.o: In function `chooseTicket':
schedule.c:(.text+0x16d): undefined reference to `qsort'
clang: error: linker command failed with exit code 1 (use -v to see invocation)
文件(schedule.c)的开头是这样的:
#include "sched.h"
#include "schedproc.h"
#include <assert.h>
#include <minix/com.h>
#include <machine/archtypes.h>
#include <stdlib.h>
#include <lib.h>
#include <string.h>
#include <time.h>
这是我使用 qsort 内置函数的函数
int chooseTicket(int* ticketList,int length,int totalTicket){
int randomValue;
int temp=0,prevTemp=0,selectedTicket=0,selectedIndex = 0;
time_t t;
struct schedproc *rmp;
int* sortedTicketList = malloc(length*sizeof(int));
memcpy(sortedTicketList,ticketList,length);
srandom((unsigned)time(&t));
randomValue = (random() % totalTicket);
qsort(sortedTicketList,length,sizeof(int),cmpFunc);//this line
注意:“rand()”和“srand()”函数也出现了相同的错误,而我使用了“random()”和“srandom()”,然后问题就解决了。我不明白尽管“rand()”和“srand()”是普遍接受的函数并且头文件包含这些函数,但为什么当我使用“rand()”和“srand( )。
最佳答案
首先,qsort
不是 built-in ,但 C standard library 的一部分(正式来说,适用于托管环境。)
其次,您需要了解#include
只允许访问任何给定库中的函数声明。您需要链接到该库,以便您的程序实际执行对功能的调用。由于您在此处收到链接器错误,因此任何#include
都无济于事。
我猜您正在编写一个 MINIX 服务,因此与 libminc
链接,而不是与完整的标准库(“libc
”)链接;换句话说,这是一个独立的环境。而且 qsort()
并不属于 C 函数的限制集 included in libminc
.
要么专门链接到qsort.(c|o)
;或者扩展您自己的 libminc
本地版本以包含 qsort()
;或者吃掉整个蛋糕并链接到完整的libc
,也许可以通过添加DPADD+= ${LIBC}; LDADD+= -lc
到 Makefile
(我从未尝试过这样做,但它应该在某个时候起作用, according to the code ;这不是通常的做法,所以期待 future 的问题。)
关于clang 链接错误 : undefined reference to 'qsort' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41191912/