[英]An interesting thing about overriding linux kernel macro
在下面的代码中,编译成功并打印1024
#include <stdio.h>
#define FD_SETSIZE 512
#include <sys/types.h>
int main()
{
printf("%d\n", FD_SETSIZE);
}
但是在下面的代码中,它编译失败并打印
test.c:4:1: warning: "FD_SETSIZE" redefined In file included from /usr/include/sys/types.h:220, from test_fd.c:3: /usr/include/sys/select.h:81:1: warning: this is the location of the previous definition
该代码是
#include <stdio.h>
#include <sys/types.h>
#define FD_SETSIZE 512
int main()
{
printf("%d\n", FD_SETSIZE);
}
有人可以解释吗? 谢谢!
但是在下面的代码中,它编译失败并打印
在问题中,两个程序都已编译,但是在编译第一个程序时,您会在预处理器阶段收到警告。
预处理阶段负责宏的替换。
在此示例中,预处理程序正在使用最后定义的宏并将其替换。
#include <stdio.h>
#define FD_SETSIZE 512
#include <sys/types.h>
FD_SETSIZE的定义在.c文件和头文件sys / types.h中都存在。 包含文件后,将完成宏的替换,因此将替换最新定义的宏。
因此,最终替换FD_SETSIZE将与sys / types.h文件中定义的相同,反之亦然。
希望这会有所帮助。
您可以使用#undef指令删除已定义的宏,并在以后替换它
#ifdef MACRO
#undef MACRO
#endif
#define MACRO
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.