Conditional Compilation

From ACENET
Jump to: navigation, search
Main page: Compilers

There are several syntax styles one could use for conditional compilation statements in the source code. Some compilers understand more than one style. However, almost every compiler can use a C-style pre-processor, thus the C-style syntax is the common denominator for the majority of compilers. Particularly, it works for IBM, Intel, PGI, Sun Studio compilers. There is a lot of documentation about the C pre-processor on the Internet.

Now, let's consider an example when you have one source file with some conditional statements, and you want to generate different executables.

$ cat hello.f90
program hello

implicit none

#if defined(HELLO)
 write(*,'("Hello world")')
#else
 write(*,'("Bye world")')
#endif

end program hello

We generate different executables like so:

$ pgf90 -Mpreprocess -o hello hello.f90
$ ./hello
Bye world

$ pgf90 -Mpreprocess -DHELLO -o hello hello.f90
$ ./hello
Hello world

Now, let's consider another example. Imagine that you want to be able to compile your code with PGI and IBM compilers. However, due to some differences in standard implementation, the IBM compiler does not generate a proper code. After some investigation you found a workaround, and you want to incorporate it into your code using conditional compilation. So, ultimately you need to distinguish inside your program which compiler is being used to compile it. Then the source code could look like this:

#if defined(__IBMC__)
 do the trick
#endif

Here are some variable that can be used to detect which compiler is used:

Intel Compiler: __INTEL_COMPILER
IBM compiler: __IBMC__
Sun Studio: __SUNPRO_F90

In this case you do not need to export any variables to the pre-processor using -D, as in the previous example. These variable are predefined within the compiler itself.