0

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?

Padmanava
  • 27
  • 7
  • quick Google search showed it's not implemented for Linux. look for alternatives. – Oleksandr Kravchuk May 18 '18 at 13:27
  • Neither the `sysctlbyname` function nor the sysctl variables you are trying to access exist on Linux. – Ian Abbott May 18 '18 at 13:31
  • @Ian Abbott On which OS is the function available? – Padmanava May 18 '18 at 13:37
  • @Padmanava - Let us Google that for you: [`sysctlbyname(3)` man page](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/sysctlbyname.3.html) and [`sysctlbyname (3)` man page](https://www.freebsd.org/cgi/man.cgi?sysctl(3)). – jww May 19 '18 at 08:41
  • In Linux, these details can be obtained by reading the kernel-provided pseudofiles [`/proc/cpuinfo`](http://man7.org/linux/man-pages/man5/proc.5.html) and [`/proc/meminfo`](http://man7.org/linux/man-pages/man5/proc.5.html). – Nominal Animal May 19 '18 at 12:58

0 Answers0