Department of Engineering

IT Services

Compilers

The Fortran77, Fortran9x, C and C++ compilers installed on the central system work in very similar ways. Creating an executable program from source code involves two main steps; compiling the source files to produce object code files, and linking the object files to form an executable file.

The names of Fortran source files by convention have the suffix .f or (for fortran 90) .f90, C source files have .c and C++ source files have .cc or .C.

Compiling a Single Source File

If the program is contained in only one file then the compilation and linking together can be performed in one step. The commands for each of the languages mentioned above are as follows:

  • C++ - g++ -g myprog.cc -o myprog
  • C - gcc -g myprog.c -o myprog
  • gfortran (supports various standards - f95, f2003 etc) - gfortan -g myprog.f -o myprog
  • fortran90 - ifort -g myprog.f90 -o myprog

The -g option tells the compiler to include debugging information (so that bugs are easier to fix) and the -o myprog part instructs it to name the executable program myprog in each case. If the -o flag is not present the name of the executable is a.out.

Compiling Multiple Source Files

If the program is composed of several source files then these must be compiled individually to produce object files with the suffix .o. These .o files are then linked to generate the program (called complete_prog, say).

   g++ -g -c firstprog.cc
   g++ -g -c secprog.cc
   g++ -g firstprog.o secprog.o -o complete_prog

The -c flag makes the compiler generate .o files rather than attempting to create a complete executable program.

If you're writing a program that has many source files, it's worth learning about Makefiles (the Computing Service has a document about make or IDEs (Integrated Development Environments - anjuta might be installed, for example)

If a library is required by a program then this must be introduced at the linking stage using the -l flag. For example, to link in the X11 library the last command would be changed to

   g++ -g firstprog.o secprog.o -o complete_prog -lX11

For the C++ compiler we use a graphical front-end (geany) that tries to add the appropriate options automatically, and copes with multiple source files.

Mixing languages

See Mixing Languages on linux