【问题标题】:Implicit declaration of timersub() function in Linux - what must I define?Linux 中 timersub() 函数的隐式声明 - 我必须定义什么?
【发布时间】:2016-12-03 21:28:50
【问题描述】:

我正在尝试在 linux 中编译 timersub() 函数,但我总是得到:

test.c: In function ‘main’:
test.c:27:2: warning: implicit declaration of function ‘timersub’ [-Wimplicit-function-declaration]
  timersub(&now, &then, &diff);
  ^

/tmp/ccLzfLsl.o: In function `main':
test.c:(.text+0x55): undefined reference to `timersub'
collect2: error: ld returned 1 exit status

这只是我使用的所有库的函数的简单代码..

#define _XOPEN_SOURCE
#define _POSIX_SOURCE
#include <stdio.h>

#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include "openflow.h"
#include "cbench.h"
#include "fakeswitch.h"
#include <unistd.h>



int main()
{
    struct timeval now, then, diff;


    gettimeofday(&then,NULL);

    sleep(1);

    gettimeofday(&now, NULL);

    timersub(&now, &then, &diff);

return 0;


} 

我正在编译它:

gcc --std=c99 -Wall -DTRACE -o test test.c

【问题讨论】:

    标签: c ubuntu gcc


    【解决方案1】:

    请参阅manual。它不在 POSIX 中,而是在 BSD 函数中。所以你需要_BSD_SOURCE

    在顶部定义它:

    #define _BSD_SOURCE
    

    或者编译:

    gcc --std=c99 -Wall -DTRACE -D_BSD_SOURCE -o test test.c 
    

    自 Glibc 2.20 起,宏 _BSD_SOURCE 已被弃用,并已被 _DEFAULT_SOURCE 取代。来自feature test macros

    _DEFAULT_SOURCE(从 glibc 2.19 开始)

    这个宏可以定义为 确保即使在 否则默认值将被禁用,就像个人 宏被显式定义,或者编译器在其中之一中调用 它的“标准”模式(例如,cc -std=c99)。定义 _DEFAULT_SOURCE 无需定义其他单独的宏或调用编译器 它的“标准”模式之一无效。

    “默认”定义包括 POSIX.1-2008 和 ISO C99,以及最初源自 BSD 的各种定义 和 System V。在 glibc 2.19 和更早版本上,这些默认值是 大致相当于明确定义以下内容:

    cc -D_BSD_SOURCE -D_SVID_SOURCE -D_POSIX_C_SOURCE=200809

    但如果您使用的是旧的 Gblic,您仍然需要使用 _BSD_SOURCE

    【讨论】:

    • 仅供参考我的 gcc 编译器现在(2016 年)说你应该使用 _DEFAULT_SOURCE,而不是 _BSD_SOURCE。
    • @moodboom 确实如此。但是在旧的 Glibc 中可能仍然需要 _BSD_SOURCE。我已经更新了答案以注意差异。
    【解决方案2】:

    基本上我只是删除了#define _XOPEN_SOURCE 和#define _POSIX_SOURCE 并仅使用 gcc -Wall -DTRACE 编译它并且它有效

    【讨论】:

      猜你喜欢
      • 2012-07-16
      • 2012-04-26
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 2017-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多