未定义的引用另一个库中的函数 [英] Undefined reference to a function in another library

查看:920
本文介绍了未定义的引用另一个库中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编译一个引用了一个lib的对象代码。这是libexample.c的代码:

  #includelibexample.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);
}

以及示例程序的简单代码:

  #includelibexample.h

int main(){
init();
返回0;
}

我使用它来编译:

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

当我尝试使用第二行进行编译时,我得到了这个结果:

  ./ libexample.so:对`timer_create'的未定义引用
./libexample.so:对`timer_settime'的未定义引用



任何人都知道我在做什么错了?

解决方案

man timer_create 命令解释你:

 名称
timer_create - 创建一个POSIX每进程计时器

概要
#include< signal.h>
#include< time.h>

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

与-lrt链接。

所以你应该像文档所说的那样链接 -lrt

因此,使用

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

生成您的 libexample .so



由于 undur_gongor 注释,你需要在所有剩下的部分(通常顺序为 gcc 参数是源文件,目标文件,依赖顺序的库)在 gcc ld 命令中(并且记录在 ld 文档,并在 gcc ones)。所以 -lrt 应该放在最后。



并学会阅读手册页。


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?

解决方案

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.

这篇关于未定义的引用另一个库中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆