当我编译以下程序时(我从 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
对我来说,这表明了两件事, header 本身被包含在内,但并不真正包含其工作所需的函数/宏,因为这意味着编译器希望它稍后能找到该函数,无论如何它都会尝试继续,但是尝试链接时失败。
但是如果我使用以下命令进行编译(只需删除 -std=c99
):
gcc endian_test.c -o endian
一切都像黄油一样顺利并且有效。知道为什么会发生这种情况以及我可以采取什么措施来补救吗?对我来说,内核给出的函数根据我编译时使用的标准而变化是没有意义的(或者我在这一点上是错误的吗?)?
提前致谢!
最佳答案
如果没有显式的 -std=
选项,调用 gcc
与 -std=gnu89
相同,意味着 C89 + GNU 扩展。 GNU 扩展将启用宏,从而使函数能够出现在 header 中。
关于c - 使用 -std=c99 编译时,be64toh 未链接或声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19525378/