error on using libblkid

3k Views Asked by At

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
2

There are 2 best solutions below

0
On BEST ANSWER

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
0
On

The error you show comes from the linker.

If you compile one single file to a .o file without linking, no external references will be tried to fulfill.

But if you want to compile into an executable, all needed requirements must be fulfilled. If the program requires the presence of a blkid_do_probe(), you should provide it somehow. Probably this will be done by linking with the appropriate library. As someone mentionned in a comment, this is to be done with -lblkid.