Daniel Otero
Daniel Otero

Reputation: 138

Undefined reference to a function in another library

I'm trying to compile an object code with a reference to one lib. This is the code of libexample.c:

#include "libexample.h"
#include <signal.h>
#include <time.h>

timer_t sched;
struct itimerspec timer = {{0, 0}, {0, 0}};

void init() {
    struct sigaction sa;

    sigemptyset(&sa.sa_mask);
    sigaction(SIGALRM, &sa, NULL);

    timer_create(CLOCK_PROCESS_CPUTIME_ID, NULL, &sched);
    timer_settime(sched, TIMER_ABSTIME, &timer, NULL);
}

And the simple code of a example program:

#include "libexample.h"

int main() {
    init();
    return 0;
}

I use this to compile:

gcc libexample.c -c -lrt -o libexample.o
gcc example.c -lrt ibexample.o -o example

And I get this when I'm trying to compile with the second line:

./libexample.so: undefined reference to `timer_create'
./libexample.so: undefined reference to `timer_settime'

Anyone knows what I'm doing wrong?

Upvotes: 1

Views: 7357

Answers (4)

Ganesh Prasad R
Ganesh Prasad R

Reputation: 1

If you are using cmake, make sure you include the libraries using target_link_libraries(). For e.g., timer functions like timer_create() you need "rt" and for pthread you need "pthread" added using target_link_libraries().

Upvotes: 0

The man timer_create command explains you:

NAME
   timer_create - create a POSIX per-process timer

SYNOPSIS
   #include <signal.h>
   #include <time.h>

   int timer_create(clockid_t clockid, struct sigevent *sevp,
                    timer_t *timerid);

   Link with -lrt.

So you should, as documentation says, link with -lrt.

So use

 gcc libexample.c -fPIC -shared -o libexample.so -lrt

to produce your libexample.so.

As undur_gongor commented, you need to put the libraries in good order after all the rest (the usual order for gcc arguments is source files, object files, libraries in dependency order) in gcc or ld commands (and that is documented in ld documentation, and in gcc ones). So -lrt should go last.

And learn to read man pages.

Upvotes: 1

ouah
ouah

Reputation: 145909

Add -lrt to your link command. timer_create and timer_settime are not part of the C Standard library.

gcc -fPIC -shared libexample.c -lrt -o libexample.so
gcc -L. example.c -lexample -o example

Upvotes: 3

necaris
necaris

Reputation: 247

Looks like you forgot to link in the library that defines timer_create and timer_settime -- you need to add -lrt to your gcc command.

(source: http://www.kernel.org/doc/man-pages/online/pages/man2/timer_create.2.html)

Upvotes: 1

Related Questions