Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

c - Why does the preprocessor directive in one function affect the compilation of another?

Following program compiles successfully and print 1000 without even calling a foo() function from our main() function. How is it possible?

#include<stdio.h>


void foo()
{
    #define ans 1000
}

int main() {

  printf("%d", ans);
  return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

#defineis run by the preprocessor which is staged before the compiler. After the preprocessor is done, the code will look like this:

/* Everything that is inside stdio.h is inserted here */

void foo()
{
}

int main() {

  printf("%d", 1000);
  return 0;
}

And this is what actually get compiled.

The preprocessor is very important to make header files work. In them, you see this structure:

#ifndef foo
#define foo
/* The content of the header file */
#endif

Without this, the compiler would complain if a header file is included more than once. You may ask why you would want to include a header file more than once. Well, header files can include other header files. Consider this macro, which is useful for debugging. It prints the name of the variable and then the value. Note that you would have to do a separate version for different types.

#define dbg_print_int(x)  fprintf(stderr, "%s = %d", #x, x)

This is pretty versatile, so you may want to include it in a header file for own use. Since it requires stdio.h, we include it.

/* debug.h */
#include <stdio.h>
#define dbg_print_int(x)  fprintf(stderr, "%s = %d", #x, x)

What happens when you include this file and also include stdio.h in you main program? Well, stdio.h will be included twice. That's why debug.h should look like this:

/* debug.h */
#ifndef DEBUG_H
#define DEBUG_H
#include <stdio.h>
#define dbg_print_int(x)  fprintf(stderr, "%s = %d", #x, x)
#endif

The file stdio.h has the same construct. The main thing here is that this is run before the compiler. The define is a simple replacement command. It does not know anything about scope or types. However, as you can see here, there is some basic logic built into it. Another thing that the preprocessor does is to remove all the comments.

You can read more about the C preprocessor here: http://www.tutorialspoint.com/cprogramming/c_preprocessors.htm


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...