unable to compile program due to function asprintf

1

Found this code, it needed to stop throttling the CPU to 20% in Dell laptops, which occurs due to the power adapter failing to be recognized by the computer.

Tried to compile on Kubuntu and got this:

warning: implicit declaration of function ‘asprintf’; did you mean ‘vasprintf’? [-Wimplicit-function-declaration]
   47 |   if (asprintf(&concat_cmd, "%s %i", cmd, *reg_value) == -1)
      |       ^~~~~~~~
      |       vasprintf

I don’t understand why it is happening. I read that asprintf is part of the libiberty-dev. The library is installed but everything does not work. Also I added

#include <libiberty/libiberty.h>

and got the same - implicit declaration of function ‘asprintf’

tell me what to do with it?

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <libiberty/libiberty.h>

#define BUFSIZE (64)

int get_msr_value(uint64_t *reg_value) {
  const char *cmd = "rdmsr -u 0x1FC";
  char cmd_buf[BUFSIZE];

  FILE *fp;

  if ((fp = popen(cmd, "r")) == NULL) {
    printf("Error opening pipe!\n");
    return -1;
  }

  cmd_buf[strcspn(fgets(cmd_buf, BUFSIZE, fp), "\n")] = 0;
  *reg_value = atoi(cmd_buf);

  if (pclose(fp)) {
    printf("Command not found or exited with error status\n");
    return -1;
  }

  return 0;
}

int main(void) {
  const char *cmd = "wrmsr -a 0x1FC";
  char *concat_cmd;
  int ret;
  uint64_t *reg_value = &(uint64_t){ 0 };

  if ((ret = get_msr_value(reg_value))) {
    return ret;
  }

  printf("Old register value: %lu\n", *reg_value);

  *reg_value = *reg_value & 0xFFFFFFFE;  // clear bit 0

  printf("New register value: %lu\n", *reg_value);

  if (asprintf(&concat_cmd, "%s %i", cmd, *reg_value) == -1)
    return -1;

  printf("Executing: %s\n", concat_cmd);

  system(concat_cmd);
  free(concat_cmd);

  return 0;
}
c
asked on Stack Overflow Apr 19, 2020 by degradante • edited Apr 19, 2020 by chqrlie

2 Answers

1

asprintf is part of stdio.h, but you need to add #define _GNU_SOURCE at the top of your file and use -std=gnu99 when compiling.

answered on Stack Overflow Apr 19, 2020 by Shadowchaser
0

The function asprintf() is not yet part of the C Standard. It is available in the GNU libc and most likely supported on your system since it uses this C library, with a declaration in <stdio.h>.

You might need to define __GNU_SOURCE or __USE_GNU before including <stdio.h> for this declaration to be parsed by the compiler. Run man asprintf to see which feature macro to use or look inside the file /usr/include/stdio.h on your system.

Either modify the source code or add a -D__GNU_SOURCE command line argument in your CFLAGS in the Makefile.

answered on Stack Overflow Apr 19, 2020 by chqrlie

User contributions licensed under CC BY-SA 3.0