Friday, July 25, 2008

#define main

I have two files and the contents are as follows :

file :: main.h
-------------------------------------
#ifndef main
#define main

#endif
--------------------------------------

and

file :: main.cpp
-------------------------------------
#include "main.h"

int main(void)
{
return 0 ;

}

------------------------------------

This program does not compile and the error message that I get is ::

expected unqualified-id before ‘void’
expected `)' before ‘void’

After some digging I have established that the problem lies in the
lines
#ifndef main
#define main
If I change it to
#ifndef Main
#define Main
or
#ifndef MAIN
#define MAIN
etc.
the program compiles.

Turns out that the line
#define main
actually defines the macro ``main" with an empty value. When the preprocessor works on the code it replaces all instances of the word main with an empty string resulting in the compile time error as posted above.

To find out the error just see the effect of preprocessor on the code before and after changing the macro name from main to Main or MAIN or whatever.

The effect of the preprocessor can be seen with the following command :
g++ -E main.cpp

Mind you that the above command will produce lots and lots of code ( in my case about 30000 lines of code). So this is what you can do

First with the erroneous header file ::
g++ -E main.cpp > outputA

and then with the fixed header file ::
g++ -E main.cpp > outputB

now compare the files outputA and outputB with the diff utility.
diff outputA outputB
You will find that the preprocessor working on the erroneous code produces
int (void)
while the preprocessor working on the correct code produces
int main(void)


Thanks to the gurus at gnu.g++.help I could understand the error I was making !
The thread can be found here.

p.s. I work on GNU/Linux with the gcc compiler.

No comments: