Search code examples
clinuxuuidblkid

error on using libblkid


when i compile and link this code to get disk uuid:

#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <blkid/blkid.h>

int main (int argc, char *argv[]) {
  blkid_probe pr;
  const char *uuid;

  if (argc != 2) {
    fprintf(stderr, "Usage: %s devname\n", argv[0]);
    exit(1);
  }

  pr = blkid_new_probe_from_filename(argv[1]);
  if (!pr) {
    err(2, "Failed to open %s", argv[1]);
  }

  blkid_do_probe(pr);
  blkid_probe_lookup_value(pr, "UUID", &uuid, NULL);

  printf("UUID=%s\n", uuid);

  blkid_free_probe(pr);

  return 0;
}

it errors out:

/home/usr/blkid/blkid.c:15: undefined reference to `blkid_new_probe_from_filename'  
make[2]: Leaving directory `/home/usr/blkid'  
make[1]: Leaving directory `/home/usr/blkid'  
/home/usr/blkid/blkid.c:20: undefined reference to `blkid_do_probe'  
/home/usr/blkid/blkid.c:21: undefined reference to `blkid_probe_lookup_value'  
/home/usr/blkid/blkid.c:25: undefined reference to `blkid_free_probe'  

when i compile the code by the following command, the code compiles with no error

gcc    -c -g -MMD -MP -MF build/Debug/GNU-Linux-x86/blkid.o.d -o build/Debug/GNU-Linux-x86/blkid.o blkid.c

Solution

  • Try to put -lblkid into your gcc command so the linker will know that you need to link your code to that library. Be sure to put this option at the end of the command. The order of options somehow matters. From here:

    It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, ‘foo.o -lz bar.o’ searches library ‘z’ after file foo.o but before bar.o. If bar.o refers to functions in ‘z’, those functions may not be loaded.

    This command should automatically both compile and link your source code:

    gcc -o test -g -MMD -MP -MF build/Debug/GNU-Linux-x86/blkid.o.d blkid.c -lblkid