使用 -std=c99 编译时,be64toh 未链接或声明

lfx*_*ove 3 c linker compilation data-conversion endianness

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

\n\n
#include <stdint.h>\n#if defined(__linux__)\n#include <endian.h> //htobe64,be64toh\n#include <arpa/inet.h> //ntohs, ntohl, htonl, htons\n#elif defined(__FreeBSD__) || defined(__NetBSD__)\n#include <sys/endian.h>\n#elif defined(__OpenBSD__)\n#include <sys/types.h>\n#define be16toh(x) betoh16(x)\n#define be32toh(x) betoh32(x)\n#define be64toh(x) betoh64(x)\n#endif\n\nint main()\n{\n    int64_t i = 0x1212121234343434;\n    int64_t j = be64toh(i);\n    return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
gcc -std=c99 endian_test.c -o endian\n
Run Code Online (Sandbox Code Playgroud)\n\n

我收到的错误是:

\n\n
user@host ~/src/c $ gcc -std=c99 derp.c \nendian_test.c: In function \xe2\x80\x98main\xe2\x80\x99:\nendian_test.c:17:2: warning: implicit declaration of function \xe2\x80\x98be64toh\xe2\x80\x99 [-Wimplicit-function-declaration]\n  int64_t j = be64toh(i);\n  ^\n/tmp/ccYonfH4.o: In function `main\':\nendian_test.c:(.text+0x23): undefined reference to `be64toh\'\ncollect2: error: ld returned 1 exit status\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n

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

\n\n
gcc endian_test.c -o endian\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n

提前致谢!

\n

oua*_*uah 5

如果没有显式-std=选项,调用与使用 C89 + GNU 扩展的方式gcc相同。-std=gnu89GNU 扩展将启用宏,从而使函数能够出现在标头中。