I tried to compile a code using the function 'sysctlbyname' and it flashed a list of errors while compiling
/tmp/ccq6bQz6.o: In function `main':
haha.c:(.text+0x43): undefined reference to `sysctlbyname'
haha.c:(.text+0x7a): undefined reference to `sysctlbyname'
haha.c:(.text+0xae): undefined reference to `sysctlbyname'
haha.c:(.text+0xe5): undefined reference to `sysctlbyname'
haha.c:(.text+0x120): undefined reference to `sysctlbyname'
collect2: error: ld returned 1 exit status
I couldn't find out what caused it but it seems like it is something related to the sys/sysctl.h
library
The code I was working with is given below:
#include <sys/types.h>
#include <sys/sysctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main()
{
char *p = NULL;
size_t len;
sysctlbyname("hw.model", NULL, &len, NULL, 0);
p = malloc(len);
sysctlbyname("hw.model", p, &len, NULL, 0);
printf("%s\n", p);
/* CTL_MACHDEP variables are architecture dependent so doesn't work
for every one */
sysctlbyname("machdep.cpu.brand_string", NULL, &len, NULL, 0);
p = malloc(len);
sysctlbyname("machdep.cpu.brand_string", p, &len, NULL, 0);
printf("%s\n", p);
int64_t mem;
len = sizeof(mem);
sysctlbyname("hw.memsize", &mem, &len, NULL, 0);
printf("System Memory : %lld\n", mem);
return (0);
}
and the command used to compile was gcc haha.c -o haha
What is causing the problem and how do I solve it?