我正在尝试使用对一个lib的引用来编译目标代码。这是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);
}
示例程序的简单代码:
#include "libexample.h"
int main() {
init();
return 0;
}
我用它来编译:
gcc libexample.c -c -lrt -o libexample.o
gcc example.c -lrt ibexample.o -o example
当我尝试用第二行编译时,我得到了这个:
./libexample.so: undefined reference to `timer_create'
./libexample.so: undefined reference to `timer_settime'
任何人都知道我做错了什么?
答案 0 :(得分:3)
将-lrt
添加到您的链接命令。 timer_create
和timer_settime
不属于C标准库。
gcc -fPIC -shared libexample.c -lrt -o libexample.so
gcc -L. example.c -lexample -o example
答案 1 :(得分:1)
看起来您忘记在定义timer_create和timer_settime的库中链接 - 您需要将-lrt
添加到gcc
命令。
(来源:http://www.kernel.org/doc/man-pages/online/pages/man2/timer_create.2.html)
答案 2 :(得分:1)
man timer_create
命令explains你:
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.
因此,正如文档所述,您应该与-lrt
链接。
所以使用
gcc libexample.c -fPIC -shared -o libexample.so -lrt
生成libexample.so
。
正如undur_gongor所评论的那样,在{gcc
参数的通常顺序是gcc
参数的通常顺序是源文件,目标文件,依赖顺序的库)之后,你需要将库放在良好的顺序中{{ 1}}或ld
命令(以及ld
文档和gcc
文档中记录的命令)。所以-lrt
应该是最后的。
学习阅读手册页。
答案 3 :(得分:0)
如果您使用的是cmake,请确保使用target_link_libraries()
包含库。例如,timer_create()
等定时器功能需要"rt"
,而pthread
需要使用"pthread"
添加target_link_libraries()
。