Search code examples
cif-statementheaderc-preprocessoransi-c

C preprocessor Result


Which result does return this construct? I mean the result variable in main-function, and why? I know, that the example is very strange ;)

header1.h file:

extern const int clf_1;

header2.c file:

#include    "header1.h"
const  int clf_1 = 2;

test.h file:

#include <header1.h>
#define xyz clf_1
#define NC_CON 2    
#if (xyz== NC_CON)
#define test 40
#else
#define test 41
#endif

C file

#include <header1.h>
#include <test.h>
    int main(int argc,char *argv[])
    {
       int result = 0:
        if (test == 40)
        {
             result  = 40;
        }
    }

Solution

  • Read the wikipage on the C preprocessor and the documentation of GNU cpp (the preprocessor inside GCC, i.e run by gcc or g++ etc...). It is a textual thing, and it is run before the definition const int clf_1 = 2; has been processed by the compiler. A #if directive only makes sense if all the names appearing in it are preprocessor symbols (defined with #define or with -D passed on the command line of the GCC or Clang/LLVM compiler)

    Use gcc -C -E yoursource.c > yoursource.i (with some other options after gcc, probably -I. is needed ... you should #include "header1.h" etc...) then look with an editor or a pager into the generated yoursource.i (the preprocessed form)

    The world would be very different if the C preprocessor transformed ASTs; for historical reasons, the first C preprocessors were textual filters (run as a different program).