Preprocessing Go programs

Preprocessor macros can be considered integral part of C/C++ programs. From inclusion of header files to controlling the build type (Debug-vs-NonDebug or Linux-vs-Win), macros play a very important role. For example, there are many advantages of having a debug build. Adding asserts, trace points and printing useful information helps developers gain insights of a (faulty) program. On the other hand, the program can easily be build without all these ‘extra’ debug-related-code (aka release build) by using a macro-processor along with other build tools.

So I thought, how about using this macro-processor to process a Go program? Now the question arises – Isn’t cpp (the macro-processor installed on my machine) general enough to be used to process Go programs? The following text from the manual page doesn’t seem to agree:

“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.”

Nevertheless, I am giving it a shot.

So, here is a small Go program that contains a macro :

/* @file : demo.go.p */
package main

import "fmt"

func main() {

        fmt.Println("hello!")
        fmt.Println("This is a sample program to demonstrate the use of",
                    "preprocessor in a Go program..")
#ifdef EXTRA
        fmt.Println("And this is the extra text printed only when EXTRA",
                    "is defined.")
#endif
}

Now, lets try to build/run this program with/without the EXTRA macro defined.

# with EXTRA undefined
$ cpp  -P -o demo.go demo.go.p | go run demo.go
hello!
This is a sample program to demonstrate the use of preprocessor in a Go program..

# with EXTRA defined
$ cpp -DEXTRA -P -o demo.go demo.go.p | go run demo.go
hello!
This is a sample program to demonstrate the use of preprocessor in a Go program..
And this is the extra text printed only when EXTRA is defined.

I am not sure if this idea is non-refutable, but so far it has managed to convince me.