简体   繁体   中英

An interesting thing about overriding linux kernel macro

In the following code, it is compiled success and print 1024

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

int main()
{
    printf("%d\n", FD_SETSIZE);
}

But in the following code, it is compiled failed and print

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

the code is

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

int main()
{
    printf("%d\n", FD_SETSIZE);
}

Can anbody explain this? Thanks!

But in the following code, it is compiled failed and print

In the question, both the programs were compiled, but while compiling first program you got warnings in preprocessor stage.

Preprocessor stage is responsible for the replacement of macros.

In this example the preprocessor is using the last defined macro and replacing it.

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

Here the definition of FD_SETSIZE is there in both the .c file and also in header file sys/types.h. After the file inclusion, then the replacing of macros will be done,so the latest defined macro is replaced.

So the final replacement FD_SETSIZE of will be same as defined in the sys/types.h file and vice-versa.

Hope this is helpful.

you can use the #undef directive to remove the defined macro and replace it later

#ifdef MACRO
#undef MACRO
#endif

#define MACRO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM