【问题标题】:be64toh not linking or being declared when compiling with -std=c99使用 -std=c99 编译时,be64toh 未链接或未声明
【发布时间】:2013-10-22 18:17:34
【问题描述】:

当我编译以下程序时(我从64 bit ntohl() in C++? 获得的所有定义的代码似乎很合理):

#include <stdint.h>
#if defined(__linux__)
#include <endian.h> //htobe64,be64toh
#include <arpa/inet.h> //ntohs, ntohl, htonl, htons
#elif defined(__FreeBSD__) || defined(__NetBSD__)
#include <sys/endian.h>
#elif defined(__OpenBSD__)
#include <sys/types.h>
#define be16toh(x) betoh16(x)
#define be32toh(x) betoh32(x)
#define be64toh(x) betoh64(x)
#endif

int main()
{
    int64_t i = 0x1212121234343434;
    int64_t j = be64toh(i);
    return 0;
}

使用以下命令编译时出现链接错误(我正在运行 linux):

gcc -std=c99 endian_test.c -o endian

我收到的错误是:

user@host ~/src/c $ gcc -std=c99 derp.c 
endian_test.c: In function ‘main’:
endian_test.c:17:2: warning: implicit declaration of function ‘be64toh’ [-Wimplicit-function-declaration]
  int64_t j = be64toh(i);
  ^
/tmp/ccYonfH4.o: In function `main':
endian_test.c:(.text+0x23): undefined reference to `be64toh'
collect2: error: ld returned 1 exit status

这对我来说表明了两件事,标头本身已包含在内,但并未真正包含使其工作所需的函数/宏,因为这意味着编译器希望稍后它会找到该函数,但无论如何它都会尝试继续进行,但是尝试链接时失败。

但如果我使用以下命令编译(只需删除-std=c99):

gcc endian_test.c -o endian

一切都像黄油一样光滑并且有效。知道为什么会发生这种情况以及我能做些什么来补救吗?对我来说,内核给定的函数(或者我错了?)根据我在编译时使用的标准而改变是没有意义的?

提前致谢!

【问题讨论】:

  • 您始终可以自己查看文件以了解它需要什么。

标签: c compilation linker endianness data-conversion


【解决方案1】:

如果没有明确的-std= 选项,调用gcc 与使用C89 + GNU 扩展的-std=gnu89 相同。 GNU 扩展将启用宏,这将使您的标头中存在功能。

【讨论】:

  • 这同样适用于-std=gnu99吗?这是一个可行的解决方法吗?
  • 是的,它确实适用于-std=gnu99。这两个选项都定义了endian.h 中使用的__USE_BSD 宏。解决您的问题的方法是在包含endian.h 之前只使用#define __USE_BSD
  • 那也不是真正的便携吧? x) 我现在将继续使用 gnu99 作为标准。谢谢!
【解决方案2】:

如果您看到be64toh 手册,您会看到它需要定义_BSD_SOURCE。所以在 Linux 上 #define 在你包含 &lt;endian.h&gt; 之前。

【讨论】:

    【解决方案3】:

    我遇到了这个问题。解决方案是不仅声明

    #define _BSD_SOURCE 
    

    还有

    #define __USE_BSD
    

    https://github.com/tailhook/zerogw/pull/34/files#r32008569

    【讨论】:

      【解决方案4】:

      最近对 glibc 的更改意味着您需要

      #define _DEFAULT_SOURCE
      

      而不是

      #define _BSD_SOURCE
      

      Deprecation of _BSD_SOURCE and _SVID_SOURCE feature macros

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-04
        • 2012-02-28
        • 2015-02-15
        • 1970-01-01
        • 1970-01-01
        • 2018-03-05
        相关资源
        最近更新 更多