| Fortran User's Guide |
Using Sun Fortran Compilers
This chapter describes how to use the Fortran 77 and Fortran 95 compilers.
The principal use of any compiler is to transform a program written in a procedural language like Fortran into a data file that is executable by the target computer hardware. As part of its job, the compiler may also automatically invoke a system linker to generate the executable file.
The Sun Fortran 77 and Fortran 95 compilers can also be used to:
- Generate a parallelized executable file for multiple processors (
-parallel).- Analyze program consistency across source files and subroutines and generate a report (
-Xlist).- Transform source files into:
- Relocatable binary (
.o) files, to be linked later into an executable file or static library (.a)file.- A dynamic shared library (
.so) file (-G).- Link files into an executable file.
- Compile an executable file with runtime debugging enabled (
-g).- Compile with runtime statement or procedure level profiling (
-pg).- Compile an executable file with runtime parallelized loop profiling (
-Zlp).- Check source code for ANSI standards conformance (
-ansi).A Quick Start
This section provides a quick overview of how to use the Sun Fortran compilers to compile and run Fortran programs. A full reference to command-line options appears in the next chapter.
Note The command line examples in this chapter primarily showf77usages. Except where noted, equivalent usages off95are similarly valid; however, the printed output may be slightly different.
The very basic steps to running a Fortran application involve using an editor to create a Fortran source file with a
.f,.for,.f90,.f95,.F,.F90, or.F95filename suffix; invoking the compiler to produce an executable; and finally, launching the program into execution by typing the name of the file:Example: This program displays a message on the screen:
demo%cat greetings.fPROGRAM GREETINGSPRINT *, 'Real programmers write Fortran!'ENDdemo%f77 greetings.fgreetings.f:MAIN greetings:demo%a.outReal programmers write Fortran!demo%In this example,
f77compiles source filegreetings.fand links the executable program onto the file,a.out, by default. To launch the program, the name of the executable file,a.out, is typed at the command prompt.Traditionally, UNIX compilers write executable output to the default file called
a.out. It can be awkward to have each compilation write to the same file. Moreover, if such a file already exists, it will be overwritten by the next run of the compiler. Instead, use the-ocompiler option to explicitly specify the name of the executable output file:
demo%f77 -o greetings greetings.fgreetings.f:MAIN greetings:demo%In the preceding example, the
-ooption tells the compiler to write the executable code to the filegreetings. (By convention, executable files usually are given the same name as the main source file, but without an extension.)Alternatively, the default
a.outfile could be renamed via themvcommand after each compilation. Either way, run the program by typing the name of the executable file:
demo%greetingsReal programmers write Fortran!demo%Here is the same example, using
f95:
demo%cat greetings.f95program greetingsprint*, 'Real programmers write Fortran 95!'enddemo%f95 -o greetings greetings.f95demo%greetingsReal programmers write Fortran 95!demo%The next sections of this chapter discuss the conventions used by the
f77andf95commands, compiler source line directives, and other issues concerning the use of these compilers. The next chapter describes the command-line syntax and all the options in detail.Invoking the Compiler
The syntax of a simple compiler command invoked at a shell prompt is:
f77[options] files... invokes the Fortran 77 compilerf95[options] files... invokes the Fortran 95 compiler
Here files... is one or more Fortran source file names ending in
.f,.F,.f90,.f95,.F90,.F95, or .for; options is one or more of the compiler option flags. (Files with names ending in a.f90or.f95extension are "free-format" Fortran 95 source files recognized only by thef95compiler.)In the example below,
f95is used to compile two source files to produce an executable file namedgrowthwith runtime debugging enabled:
demo%f95 -g -o growth growth.f fft.f95
Note You can invoke the Sun WorkShop 6 Fortran 95 compiler with either thef95orf90command --f90is now an alias forf95.
Compile-Link Sequence
In the previous example, the compiler automatically generates the loader object files,
growth.oandfft.o, and then invokes the system linker to create the executable program filegrowth.After compilation, the object files,
growth.oandfft.o,will remain. This convention permits easy relinking and recompilation of files.If the compilation fails, you will receive a message for each error. No
.ofiles are generated for those source files with errors, and no executable program file is written.Command-Line File Name Conventions
The suffix extension attached to file names appearing on the command-line determine how the compiler will process the file. File names with a suffix extension other than one of those listed below, or without an extension, are passed to the linker.
Fortran 95 free-format is described in Appendix C of this manual.
Source Files
The Fortran compilers will accept multiple source files on the command line. A single source file, also called a compilation unit, may contain any number of procedures (main program, subroutine, function, block data, module, and so on). Applications may be configured with one source code procedure per file, or by gathering procedures that work together into single files. The Fortran Programming Guide describes the advantages and disadvantages of these configurations.
Source File Preprocessors
Both
f77andf95support two source file preprocessors,fppandcpp. Either can be invoked by the compiler to expand source code "macros" and symbolic definitions prior to compilation. The compilers will usefppby default; the-xpp=cppoption changes the default fromfpptocpp. (See also the discussion of the-Dname option).
fppis a Fortran-specific source preprocessor. See thefpp(1) man page and thefppREADME for details. It is invoked by default byf77on files with a.Fextension and byf95on files with a.F,.F90, or.F95extension.The source code for
fppis available from the Netlib web site at
http://www.netlib.org/fortran/See
cpp(1) for information on the standard Unix C language preprocessor. Use offppovercppis recommended on Fortran source files.Separate Compiling and Linking
You can compile and link in separate steps. The
-coption compiles source files and generates.oobject files, but does not create an executable. Without the-coption the compiler will invoke the linker. By splitting the compile and link steps in this manner, a complete recompilation is not needed just to fix one file, as shown in the following example:Compile one file and link with others in separate steps:
demo%f95 -c file1.f(Make new object file)demo%f95 -o prgrm file1.o file2.o file3.o(Make executable file)Be sure that the link step lists all the object files needed to make the complete program. If any object files are missing from this step, the link will fail with undefined external reference errors (missing routines).
Consistent Compiling and Linking
Ensuring a consistent choice of compiling and linking options is critical whenever compilation and linking are done in separate steps. Compiling any part of a program with any of the following options requires linking with the same options:
-a, -autopar, -Bx, -fast, -G, -Lpath, -lname, -mt, -xmemalign, -nolib, -norunpath, -p, -pg, -xlibmopt, -xlic_lib=name, -xprofile=pExample: Compiling
sbr.fwith-aandsmain.fwithout it, then linking in separate steps (-ainvokestcovold-style profiling):
demo%f95 -c -a sbr.fdemo%f95 -c smain.fdemo%f95 -a sbr.o smain.olink step; passes -a to the linkerAlso, a number of options require that all source files be compiled with that option, including the link step. These include:
-autopar, -aligncommon, -dx, -dalign, -dbl, -explicitpar, -f, -misalign, -native, -parallel, -r8, -xarch=a, -xcache=c, -xchip=c, -xF, -xtarget=t, -xtypemap, -ztextLinking Mixed Fortran 95 and Fortran 77 Compilations
As a general rule, if any of the object files that make up a program were compiled with
f95, then the final link step must be done withf95. Usef77to produce the executable file only if none of the.oobject files were compiled withf95. See also Appendix , Compatibility with FORTRAN 77.Unrecognized Command-Line Arguments
Any arguments on the command-line that the compiler does not recognize are interpreted as being possibly linker options, object program file names, or library names.
- Unrecognized options (with a
-) generate warnings.- Unrecognized non-options (no
-) generate no warnings. However, they are passed to the linker and if the linker does not recognize them, they generate linker error messages.For example:
Note that in the first example,
-bitis not recognized byf95and the option is passed on to the linker (ld), who tries to interpret it. Because single letterldoptions may be strung together, the linker sees-bitas-b -i -t, which are all legitimateldoptions! This may (or may not) be what the user expects, or intended.In the second example, the user intended to type the
f77/f95option-fastbut neglected the leading dash. The compiler again passes the argument to the linker which, in turn, interprets it as a file name.These examples indicate that extreme care should be observed when composing compiler command lines!
Modules (Fortran 95)
f95automatically creates module information files for eachMODULEdeclaration encountered in the source files, and searches for modules referenced by aUSEstatement. For each module encountered (MODULEmodule_name), the compiler generates a corresponding file, module_name.mod, in the current directory. For example,f95generates the module information filelist.modfor theMODULElistunit found on filemysrc.f95.The compiler searches the current directory for module files referenced in
USEstatements. Module files must be compiled before compiling any source file referencing aMODULEin aUSEstatement. Directories can be added to the search path with the-Mcommand-line option. However, individual.modfiles cannot be specified directly on the command line.Directives
Use a source code directive, a form of Fortran comment, to pass specific information to the compiler regarding special optimization or parallelization choices. Compiler directives are also sometimes called pragmas. The compilers recognize a set of general directives and parallelization directives. Fortran 95 also processes OpenMP shared memory multiprocessing directives.
Directives unique to
f95are described in Appendix C. A complete summary of all the directives recognized byf77andf95appears in Appendix E.
Note Directives are not part of the Fortran standard.
General Directives
The various forms of a general Sun Fortran directive are:
The variable keyword identifies the specific directive. Additional arguments or suboptions may also be allowed. (Some directives require the additional keyword
SUNorSPARC, as shown above.)A general directive has the following syntax:
- In column one, any of the comment-indicator characters
c,C,!, or*- For
f95free-format,!is the only comment-indicator recognized (!$PRAGMA). The examples in this chapter assume fixed-format.- The next seven characters are
$PRAGMA, no blanks, in either uppercase or lowercase- With
f77, directives using the!comment-indicator character may appear in any position on the line. Withf95, this is only possible for free-format source programs.Observe the following restrictions:
- After the first eight characters, blanks are ignored, and uppercase and lowercase are equivalent, as in Fortran text.
- Because it is a comment, a directive cannot be continued, but you can have many
C$PRAGMAlines, one after the other, as needed.- If a comment satisfies the above syntax, it is expected to contain one or more directives recognized by the compiler; if it does not, a warning is issued.
- The C preprocessor,
cpp, will expand macro symbol definitions within a comment or directive line; the Fortran preprocessor,fpp, will not expand macros in comment lines.fppwill recognize legitimatef77andf95directives and allow limited substitution outside directive keywords. However, be careful with directives requiring the keywordSUN.cppwill replace lower-casesunwith a predefined value. Also, if you define acppmacroSUN, it might interfere with theSUNdirective keyword. A general rule would be to spell those pragmas in mixed case if the source will be processed bycpporfpp, as in:
C$PRAGMA Sun UNROLL=3The Fortran compilers recognize the following general directives:
The C Directive
The
C()directive specifies that its arguments are external functions. It is equivalent to anEXTERNALdeclaration except that unlike ordinary external names, the Fortran compiler will not append an underscore to these argument names. See the C-Fortran Interface chapter in the Fortran Programming Guide for more details.The
C()directive for a particular function should appear before the first reference to that function in each subprogram that contains such a reference.Example - compiling
ABCandXYZforC:
EXTERNAL ABC, XYZC$PRAGMA C(ABC, XYZ)The
UNROLLDirectiveThe
UNROLLdirective requires that you specifySUNafterC$PRAGMA.The
C$PRAGMA SUN UNROLL=n directive instructs the compiler to unroll loops n times during its optimization pass. (The compiler will unroll loops only when its analysis regards such unrolling as appropriate.)n is a positive integer. The choices are:
- If n=1, the optimizer may not unroll any loops.
- If n>1, the optimizer may unroll loops n times.
If any loops are actually unrolled, the executable file becomes larger. For further information, see the Fortran Programming Guide chapter on performance and optimization.
Example - unrolling loops two times:
C$PRAGMA SUN UNROLL=2The
WEAKDirectiveThe
WEAKdirective defines a symbol to have less precedence than an earlier definition of the same symbol. This pragma is used mainly in sources files for building libraries. The linker does not produce an error message if it is unable to resolve a weak symbol.
C$PRAGMA WEAK (name1 [=name2])
WEAK(name1) defines name1 to be a weak symbol. The linker does not produce an error message if it does not find a definition for name1.
WEAK(name1=name2) defines name1 to be a weak symbol and an alias for name2.If your program calls but does not define name1, the linker uses the definition from the library. However, if your program defines its own version of name1, then the program's definition is used and the weak global definition of name1 in the library is not used. If the program directly calls name2, the definition from library is used; a duplicate definition of name2 causes an error. See the Solaris Linker and Libraries Guide for more information.
The
OPTDirectiveThe
OPTdirective requires that you specifySUNafterC$PRAGMA.The
OPTdirective sets the optimization level for a subprogram, overriding the level specified on the compilation command line. The directive must appear immediately before the target subprogram, and only applies to that subprogram. For example:
C$PRAGMA SUN OPT=2SUBROUTINE smart(a,b,c,d,e)...etcWhen the above is compiled with an
f77command that specifies-O4, the directive will override this level and compile the subroutine at-O2. Unless there is another directive following this routine, the next subprogram will be compiled at-O4.The routine must also be compiled with the
-xmaxopt=n option for the directive to be recognized. This compiler option specifies a maximum optimization value forPRAGMA OPTdirectives: if aPRAGMA OPTspecifies an optimization level greater than the-xmaxoptlevel, the-xmaxoptlevel is used.(SPARC Only) The
PIPELOOP=n DirectiveThe
PIPELOOP=n directive requires that you specifySUNafterC$PRAGMA.This directive must appear immediately before a DO loop. n is a positive integer constant, or zero, and asserts to the optimizer a dependence between loop iterations. A value of zero indicates that the loop has no inter-iteration dependencies and can be freely pipelined by the optimizer. A positive n value implies that the I-th iteration of the loop has a dependency on the (I-n)-th iteration, and can be pipelined at best for only n iterations at a time.
C We know that the value of K is such that there can be noC cross-iteration dependencies (E.g. K>N)C$PRAGMA SUN PIPELOOP=0DO I=1,NA(I)=A(I+K) + D(I)B(I)=B(I) + A(I)END DOFor more information on optimization, see the Fortran Programming Guide.
(SPARC Only)
PREFETCHDirectivesThe
-xprefetchoption flag, page 109, enables a set ofPREFETCHdirectives that advise the compiler to generate prefetch instructions for the specified data element. Prefetch instructions are only available on UltraSPARC platforms.
C$PRAGMA SPARC_PREFETCH_READ_ONCE(name)C$PRAGMA SPARC_PREFETCH_READ_MANY(name)C$PRAGMA SPARC_PREFETCH_WRITE_ONCE(name)C$PRAGMA SPARC_PREFETCH_WRITE_MANY(name)See also the C User's Guide, or the SPARC Architecture Manual, Version 9 for further information about prefetch instructions.
Parallelization Directives
Parallelization directives explicitly request the compiler attempt to parallelize the
DOloop or the region of code that follows the directive. The syntax differs from general directives. Parallelization directives are only recognized when compilation options-parallelor-explicitparare used. Details regarding Fortran parallelization can be found in the Fortran Programming Guide.
Note Fortran parallelization features require a Sun WorkShop HPC license.
The Fortran compilers support three styles of parallelization directives, Sun, Cray, and OpenMP.
Sun style parallelization directives are the default (explicitly selected with the compiler option
-mp=sun). Sun directives have the directive sentinel$PAR.Alternatively, Cray style parallelization directives, enabled by the
-mp=craycompiler option, have the sentinelMIC$. Interpretations of similar directives differ between Sun and Cray styles. See the chapter on parallelization in the Fortran Programming Guide for details.Fortran 95 also accepts OpenMP parallelization directives, described in the next section.
Sun/Cray parallelization directives have the following syntax:
- The first character must be in column one.
- The first character can be any one of
c,C,*, or!.- The next four characters may be either
$PAR(Sun style), orMIC$(Cray style), without blanks, and in either upper or lower case.- Next, the directive keyword and qualifiers, separated by blanks. The explicit parallelization directive keywords are:
TASKCOMMON,DOALL, DOSERIAL,andDOSERIAL*Each parallelization directive has its own set of optional qualifiers that follow the keyword.
Example: Specifying a loop with a shared variable:
C$PAR DOALL SHARED(yvalue) Sun styleCMIC$ DOALL SHARED(yvalue) Cray styleSee Appendix E for a summary, and the Fortran Programming Guide for details about parallelization and these directives.
OpenMP Directives
The Sun WorkShop 6 Fortran 95 compiler recognizes the OpenMP Fortran shared memory multiprocessing API as specified by the OpenMP Architecture Review Board. See the OpenMP website for details:
http://www.openmp.org/.You must compile with the command-line option -
-mp=openmp, or-openmp, to enable OpenMP directives.A summary of OpenMP directives appears in Appendix E.
OpenMP directives can be used in conjunction with either Sun or Cray style parallelization directives, as long as these different directives are not nested within each other. To enable OpenMP with Sun or Cray directives, use
-mp=openmp,sunor-mp=openmp,cray(no spaces), respectively.Compiler Usage Tips
The next sections suggest a number of ways to use the Sun Fortran compilers efficiently. A complete compiler options reference follows in the next chapter.
Determining Hardware Platform
Some compiler flags allow the user to tune code generation to a specific set of hardware platform options. The utility command
fpversiondisplays the hardware platform specifications for the native processor:
The values printed depend on the load on the system at the moment
fpversionis called.See
fpversion(1) and the Numerical Computation Guide for details.Using Environment Variables
You can specify options by setting the
FFLAGSorOPTIONSvariables.Either
FFLAGSorOPTIONScan be used explicitly in the command line. When you are usingmakefiles implicit compilation rules,FFLAGSis used automatically by themakeprogram.Example: Set
FFLAGS: (C Shell)
demo%setenv FFLAGS '-fast -Xlist'Example: Use
FFLAGSexplicitly:
demo%f95 $FFLAGS any.fWhen using
make, if theFFLAGSvariable is set as above and the makefile's compilation rules are implicit, that is, there is no explicit compiler command line, then invokingmakewill result in a compilation equivalent to:
makeis a very powerful program development tool that can easily be used with all Sun compilers. See themake(1) man page and the Program Development chapter in the Fortran Programming Guide.
Note Default implicit rules assumed bymakemay not recognize files with extensions.f95and.mod(Fortran 95 Module files). See the Fortran Programming Guide and the Fortran 95 README for details.
Memory Size
A compilation may need to use a lot of memory. This will depend on the optimization level chosen and the size and complexity of the files being compiled. On SPARC platforms, if the optimizer runs out of memory, it tries to recover by retrying the current procedure at a lower level of optimization and resumes subsequent routines at the original level specified in the
-On option on the command line.A workstation should have at least 24 megabytes of memory; 32 megabytes are recommended. Memory usage depends on the size of each procedure, the level of optimization, the limits set for virtual memory, the size of the disk swap file, and various other parameters.
Compiling a single source file containing many routines could cause the compiler to run out of memory or swap space.
If the compiler runs out of memory, try reducing the level of optimization, or split multiple-routine source files into files with one routine per file, using
fsplit(1).Swap Space Limits
The command,
swap-s, displays available swap space. See swap(1M).Example: Use the
swapcommand:
demo%swap -stotal: 40236k bytes allocated + 7280k reserved = 47516k used, 1058708k available
To determine the actual real memory:
demo%/usr/sbin/dmesg | grep memmem = 655360K (0x28000000)avail mem = 602476544Increasing Swap Space
Use
mkfile(1M) andswap(1M) to increase the size of the swap space on a workstation. You must become superuser to do this.mkfilecreates a file of a specific size, andswap-aadds the file to the system swap space:
demo#mkfile -v 90m /home/swapfile/home/swapfile 94317840 bytesdemo#/usr/sbin/swap -a /home/swapfileControl of Virtual Memory
Compiling very large routines (thousands of lines of code in a single procedure) at optimization level
-O3or higher may require additional memory that could degrade compile-time performance. You can control this by limiting the amount of virtual memory available to a single process.
- In a
shshell, use theulimitcommand. Seesh(1).
- In a
cshshell, use thelimitcommand. Seecsh(1).Each of these command lines causes the optimizer to try to recover at 16 Mbytes of data space.
This limit cannot be greater than the system's total available swap space and, in practice, must be small enough to permit normal use of the system while a large compilation is in progress.
Be sure that no compilation consumes more than half the space.
Example: With 32 Mbytes of swap space, use the following commands:
In a
shshell:
demo$ulimit -d 1600In a
cshshell:
demo%limit datasize 16MThe best setting depends on the degree of optimization requested and the amount of real and virtual memory available.
In 64-bit Solaris environments, the soft limit for the size of an application data segment is 2 Gbytes. If your application needs to allocate more space, use the shell's
limitorulimitcommand to remove the limit. Forcshuse:
demo%limit datasize unlimitedor for
shorksh:
demo$ulimit -d unlimitedSee the Solaris 64-bit Developer's Guide for more information.
|
Sun Microsystems, Inc. Copyright information. All rights reserved. Feedback |
Library | Contents | Previous | Next | Index |