5

I am trying to some get Linux kernel version information by calling uname system call, but I am getting a compiler error saying ‘struct utsname’ has no member named ‘domainname’

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/utsname.h>

#define _GNU_SOURCE

int main(void) {

   struct utsname buffer;

   errno = 0;
   if (uname(&buffer) != 0) {
      perror("uname");
      exit(EXIT_FAILURE);
   }

   printf("system name = %s\n", buffer.sysname);
   printf("node name   = %s\n", buffer.nodename);
   printf("release     = %s\n", buffer.release);
   printf("version     = %s\n", buffer.version);
   printf("machine     = %s\n", buffer.machine);

   #ifdef _GNU_SOURCE
      printf("domain name = %s\n", buffer.domainname);
   #endif

   return EXIT_SUCCESS;
}

according to https://linux.die.net/man/2/uname struct utsname is

struct utsname {
    char sysname[];    /* Operating system name (e.g., "Linux") */
    char nodename[];   /* Name within "some implementation-defined
                          network" */
    char release[];    /* Operating system release (e.g., "2.6.28") */
    char version[];    /* Operating system version */
    char machine[];    /* Hardware identifier */
#ifdef _GNU_SOURCE
    char domainname[]; /* NIS or YP domain name */
#endif
};

I am not sure what I missed here

Vaggelis Spi
  • 164
  • 2
  • 11
Melan
  • 458
  • 2
  • 15
  • 4
    The preprocessor work is a strict top-down fashion when it processes the code, which means that order matters. If you `#include` a header file before you define the macro, then the macro simply won't be defined for that included header file. – Some programmer dude Dec 09 '19 at 10:10
  • 1
    In addition to @SPD, you can also compile with the macro enabled: `gcc -D_GNU_SOURCE=1 test.c -o test.exe`. You might also be able to get the macro defined with `gcc -std=gnu99 test.c -o test.exe`. Also see questions like [_GNU_SOURCE and __USE_GNU](https://stackoverflow.com/q/7296963/608639) and [Should I still define _GNU_SOURCE when I compile with -std=gnu99?](https://stackoverflow.com/q/18676944/608639) – jww Dec 09 '19 at 10:54

1 Answers1

6

From man feature_test_macros:

NOTE: In order to be effective, a feature test macro must be defined before including any header files

It's:

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/utsname.h>
alk
  • 69,737
  • 10
  • 105
  • 255
KamilCuk
  • 120,984
  • 8
  • 59
  • 111