简体   繁体   中英

How to change #include with #define in c?

Is there a way to change the #include syntax? Here's an example of I am trying to reach out with this.

#define begin {
#define end }
#define import #include
import <stdio.h>


int main() begin
 return 0;
end

Not really. At least not in a way that would fill any practical meaning.

First, the preprocessor is run and it till change "import" to "#include", and then it gives the output to the compiler. But the compiler does not understand preprocessor directives. Also, the C language does not have any functionality to include files. That's supposed to be handled by the preprocessor.

So one thing that CAN be done, although it's not something you should ever do in production code is to run the preprocessor twice. It's very likely that this approach will yield bugs that are tricky to find.

$ cat a.c
#define begin {
#define end }
#define import #include 
import <stdio.h>
int main() begin
 return 0;
end

$ gcc -E a.c > b.c
$ cat b.c 
# 1 "a.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 31 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 32 "<command-line>" 2
# 1 "a.c"



#include <stdio.h>
int main() {
 return 0;
}

$ gcc b.c
$

You could simplify the above to one command like this:

gcc -E a.c | gcc -xc -

(The final dash is important)

Per C 2018 6.10.3.4 3, after a macro has been substituted:

The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one,…

Thus, defining a macro to expand to #include will not result in an #include directive being processed.

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