关于覆盖linux内核宏的一个有趣的事情

时间:2016-03-01 07:24:21

标签: c linux

在以下代码中,编译成功并打印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);
}

有人可以解释一下吗?谢谢!

2 个答案:

答案 0 :(得分:1)

但是在下面的代码中,编译失败并打印

在这个问题中,两个程序都已编译,但在编译第一个程序时,您会在预处理器阶段收到警告。

预处理器阶段负责替换宏。

在此示例中,预处理器使用最后定义的宏并替换它。

#include  <stdio.h>
#define  FD_SETSIZE 512
#include  <sys/types.h>

这里FD_SETSIZE的定义既存在于.c文件中,也存在于头文件sys / types.h中。 在包含文件之后,将完成宏的替换,因此替换最新定义的宏。

因此,最终替换FD_SETSIZE将与sys / types.h文件中定义的相同,反之亦然。

希望这有用。

答案 1 :(得分:0)

您可以使用#undef directive删除已定义的宏并稍后将其替换

#ifdef MACRO
#undef MACRO
#endif

#define MACRO