Type of #define variables

后端 未结 7 2166
一个人的身影
一个人的身影 2020-11-27 17:33

If I have:

#define MAXLINE    5000

What type is MAXLINE understood to be? Should I assume it is an int? Can I test it somehow?

相关标签:
7条回答
  • 2020-11-27 18:36

    MAXLINE is not a variable at all. In fact, it is not C syntax. Part of the compilation process runs a preprocessor before the compiler, and one of the actions the preprocessor takes is to replace instances of MAXLINE tokens in the source file with whatever comes after #define MAXLINE (5000 in the question's code).

    Aside: another common way you use the preprocessor in your code is with the #include directive, which the preprocessor simply replaces with the preprocessed contents of the included file.

    Example

    Let's look at an example of the compilation process in action. Here's a file, foo.c, that will be used in the examples:

    #define VALUE 4
    
    int main()
    {
      const int x = VALUE;
      return 0;
    }
    

    I use gcc and cpp (the C preprocessor) for the examples, but you can probably do this with whatever compiler suite you have, with different flags, of course.

    Compilation

    First, let's compile foo.c with gcc -o foo.c. What happened? It worked; you should now have an executable foo.

    Preprocessing only

    You can tell gcc to only preprocess and not do any compilation. If you do gcc -E foo.c, you will get the preprocessed file on standard out. Here's what it produces:

    # 1 "foo.c"
    # 1 "<built-in>"
    # 1 "<command-line>"
    # 1 "foo.c"
    
    
    int main()
    {
      const int x = 4;
      return 0;
    }
    

    Notice that the first line of main has replaced VALUE with 4.

    You may be wondering what the first four lines are. Those are called linemarkers, and you can read more about them in Preprocessor Output.

    Compilation without preprocessing

    As far as I know, you cannot outright skip preprocessing in gcc, but a couple approaches exist to tell it that a file has already been preprocessed. Even if you do this, however, it will remove macros present in the file because they are not for compiler consumption. You can see what the compiler works with in this situation with gcc -E -fpreprocessed foo.c:

    .
    .
    .
    .
    int main()
    {
      const int x = VALUE;
      return 0;
    }
    

    Note: I put the dots in at the top; pretend those are blank lines (I had to put them there to get those lines to be displayed by SO).

    This file clearly will not compile (try gcc -fpreprocessed foo.c to find out) because VALUE is present in the source, but not defined anywhere.

    0 讨论(0)
提交回复
热议问题