Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Libelf : Undefined Reference for functions

I am trying to use Libelf library to get some info on some elf files. But I keep getting these "undefined reference to [...]". I installed the libelf from the synaptic (tried to get from website too), and the lib seems to be instaled okay.

My code :

#include <err.h>
#include <fcntl.h>
#include <sysexits.h>
#include <unistd.h>

#include <stdio.h>
#include <stdlib.h>
#include <libelf.h>

int main(int argc, char * argv[]) {
    Elf *elf_file;
    Elf_Kind  elf_kind_file;
    int file_descriptor;

    if((argc!=2)) 
        printf("Argumento em formato nao esperado\n");

    file_descriptor = open(argv[1], O_RDONLY, 0);
    elf_file = elf_begin(file_descriptor, ELF_C_READ, NULL);
    elf_kind_file = elf_kind(elf_file);

    elf_end(elf_file);
    close(file_descriptor);


    return 0;
}

Here is what I get from the terminal (Currently using Ubuntu 11.4):

gcc sample.c -o sample
/tmp/ccP7v2DT.o: In function `main':
sample.c:(.text+0x57): undefined reference to `elf_begin'
sample.c:(.text+0x67): undefined reference to `elf_kind'
sample.c:(.text+0x77): undefined reference to `elf_end'
collect2: ld returned 1 exit status

UPDATE

Solved all but one of my problems putting -lelf before my file during the compiling. The last one I could only solve updating my libelf to a new version (that wasn't available on the Synaptic Manager):

wget http://ftp.br.debian.org/debian/pool/main/e/elfutils/libelf-dev_0.153-1_i386.deb
wget http://ftp.br.debian.org/debian/pool/main/e/elfutils/libelf1_0.153-1_i386.deb
sudo dpkg -i libelf-dev_0.153-1_i386.deb libelf1_0.153-1_i386.deb
like image 435
albf.unicamp Avatar asked Sep 10 '25 19:09

albf.unicamp


1 Answers

You probably need to link to the library. The standard way to do this is:

gcc sample.c -l elf -o sample

This searches the standard library directories for libelf.a, and includes the relevant object files in that archive into the build. Assuming the library has been installed correctly, libelf.a or a similarly-named file should exist.

like image 104
ideasrule Avatar answered Sep 13 '25 08:09

ideasrule