midor
midor

Reputation: 5557

C static library cannot link with librt

I have to create a static library (it is not an option to create a dynamic one), and I have a function in this static library which uses timer_create from time.h e.g. something like this:

somelib.h:

#include <time.h>

int do_something(void);

somelib.c:

int do_something(void){
        timer_t timer;
        struct sigevent sevp;
        sevp.sigev_notify = SIGEV_SIGNAL;
        sevp.sigev_signo = SIGRTMIN;
        sevp.sigev_value.sival_ptr = NULL;
        int ret = timer_create(CLOCK_MONOTONIC, &sevp, &timer);
        timer_delete(timer);
        return 0;
}

The code is actually meaningless and just there to make is necessary to link against librt to illustrate my prolem, which is as follows:

After I compile somelib.c:

gcc -c -o somelib.o somelib.c -lrt

and make the static library:

ar rcs somelib.a somelib.o

I get the following error when linking against it:

gcc -o someexec someexec.c -lrt ./somelib.a

returns:

somelib.c:(.text+0x30): undefined reference to `timer_create'
somelib.c:(.text+0x44): undefined reference to `timer_destroy'

This is a minimum example for my problem. I am not sure though if this can be fixed at all, because my understanding was, that the static lib would have to know the location of librt at the time of its creation and since it is dynamic it is not possible without linking against a static version of librt. Still I don't use static libraries very often, so I would like to know if there is a way to do something like this.

Compiler version: gcc 4.8.1 No other flags set.

Upvotes: 2

Views: 6143

Answers (1)

sstn
sstn

Reputation: 3069

gcc -c -o somelib.o somelib.c -lrt

That is compilation only, the -lrt is irrelevant here.

gcc -o someexec someexec.c -lrt ./somelib.a

The order in which objects/libraries are given matters.

Try to push -lrt to the end, then it should work.

Upvotes: 8

Related Questions