tags:

views:

130

answers:

3

I'm trying to run the GCC precompiler on Java code by issuing the following command: "gcc -D YES -E -x c -o YesNo.java _YesNo.java". The gcc precompiler adds some extra stuff/info in the beginning of the file, though, as can be seen below. How do I instruct the precompiler not to create such outputs so I can compile the output of the precompiler directly without making any modifications? Thanks in advance!

Java input to GCC:

 public class YesNo
{
    public static void main(String[] args)
    {
        #ifdef YES
            System.out.println("YES");
        #else
            System.out.println("NO");
        #endif
    }
}

GCC precompiler output:

 # 1 "Slask.pjava"
 # 1 "<built-in>"
 # 1 "<command line>"
 # 1 "Slask.pjava"

 public class YesNo
 {
    public static void main(String[] args)
    {

             System.out.println("YES");



    }
 }
+4  A: 

You just need the -P arg.

You might also want to run the cpp command, rather than gcc.

Finally, note the following FSF caution from man cpp:

The C preprocessor is intended to be used only with C, C++, and Objective-C source code. In the past, it has been abused as a general text processor. It will choke on input which does not obey C’s lexical rules. For example, apostrophes will be interpreted as the beginning of character constants, and cause errors. Also, you cannot rely on it preserving characteristics of the input which are not significant to C-family languages. If a Makefile is preprocessed, all the hard tabs will be removed, and the Makefile will not work.

Having said that, you can often get away with using cpp on things which are not C. Other Algol-ish programming languages are often safe (Pascal, Ada, etc.) So is assembly, with caution. -traditional-cpp mode preserves more white space, and is otherwise more permissive. Many of the problems can be avoided by writing C or C++ style comments instead of native language comments, and keeping macros simple.

Wherever possible, you should use a preprocessor geared to the language you are writing in. Modern versions of the GNU assembler have macro facilities. Most high level programming languages have their own conditional compilation and inclusion mechanism. If all else fails, try a true general text processor, such as GNU M4.

Note the reference to m4(1). I suspect cpp will work fine on Java, but if it doesn't just use m4.

DigitalRoss
A: 

Add -Wp,-P to your gcc invocation. -Wp, passes an argument to the preprocessor cpp, and -P inhibits generation of linemarkers when passed to cpp.

bdonlan
+1  A: 

Preprocessing will (in my opinion) make code brittle.

Instead consider aspectj or annotations.

Thorbjørn Ravn Andersen