Как установить gfortran на windows 10

Fortran : High-performance parallel programming language

GFortran is the name of the GNU Fortran project. The main wiki page offers many helpful links about GFortran, as well as Fortran in general. In this guide, the installation process for GFortran on Windows, Linux, macOS and OpenBSD is presented in a beginner-friendly format based on the information from GFortranBinaries.

Windows#

Three sources provide quick and easy way to install GFortran compiler on Windows:

  1. http://www.equation.com, provides 32 and 64-bit x86
    executables for GCC version 12.1.

  2. TDM GCC, provides 32 and 64-bit x86 executables for GCC version 10.3.

  3. MinGW-w64 provides a 64-bit x86 executable for GCC version 12.2.

In all the above choices, the process is straightforward—just download the installer and follow the installation wizard.

Unix-like development on Windows#

For those familiar with a unix-like development environment, several emulation options are available on Windows each of which provide packages for gfortran:

  • Cygwin: A runtime environment that provides POSIX compatibility to Windows.

  • MSYS2: A collection of Unix-like development tools, based on modern Cygwin and MinGW-w64.

  • Windows Subsystem for Linux (WSL): An official compatibility layer for running Linux binary executables on Windows. With Windows Subsystem for Linux GUI one can run text editors and other graphical programs.

All of the above approaches provide access to common shells such as bash and development tools including GNU coreutils, Make, CMake, autotools, git, grep, sed, awk, ssh, etc.

We recommend the WSL environment for those looking for a Unix-like development environment on Windows.

Linux#

Debian-based (Debian, Ubuntu, Mint, etc…)#

Check whether you have gfortran already installed

If nothing is returned then gfortran is not installed.
To install gfortran type:

sudo apt install gfortran

to check what version was installed type:

You can install multiple versions up to version 10 (on Ubuntu 22.04) by typing the version number immediately after “gfortran”, e.g.:

sudo apt install gfortran-8

To install newer versions on older Ubuntu releases, you will first need to add the following repository, update, and then install:

sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt update
sudo apt install gfortran-10

Finally, you can switch between different versions or set the default one with the update-alternatives (see manpage). There are many online tutorials on how to use this feature. A well structured one using as an example C and C++ can be found here, you can apply the same logic by replacing either gcc or g++ with gfortran.

RPM-based (Red Hat Enterprise Linux, CentOS, Fedora, openSUSE)#

sudo yum install gcc-gfortran

Since Fedora 22 and Red Hat Enterprise Linux 8, dnf is the default package manager:

sudo dnf install gcc-gfortran

Arch-based (Arch Linux, EndeavourOS, Manjaro, etc…)#

sudo pacman -S gcc-fortran

macOS#

Xcode#

If you have Xcode installed, open a terminal window and type:

Binaries#

Go to fxcoudert/gfortran-for-macOS to directly install binaries.

Homebrew#

Fink#

GNU-gcc Package link

MacPorts#

Search for available gcc versions:

Install a gcc version:

OpenBSD#

On OpenBSD, the GFortran executable is named egfortran. To test it, type:


OpenCoarrays#

OpenCoarrays is an open-source software project that produces an application binary interface (ABI) used by the GNU Compiler Collection (GCC) Fortran front-end to build executable programs that leverage the parallel programming features of Fortran 2018. Since OpenCoarrays is not a separate compiler, we include it here, under gfortran.

While with gfortran you can compile perfectly valid code using coarrays, the generated binaries will only run in a single image (image is a Fortran term for a parallel process), that is, in serial mode. OpenCoarrays allows running code in parallel on shared- and distributed-memory machines, similar to MPI:

cafrun -n <number_of_images> <executable_name>

The process of installation is provided in a clear and comprehensive manner on the official site.

We emphasize that native installation on Windows is not possible. It is only possible through WSL.

February 2020

Back to index.html.

Installation of GFortran in Windows 10

This article explains how to install GFortran in Windows 10. GFortran is a free Fortran compiler. The users can use it with no charge. GFortran is a product of an “open source” project to develop a collection of free compilers (GCC).

The compiler is the most useful when combining with other commands of Linux/Unix. Because Windows does not have the commands by default, programmers developed some packages to have the commands in Windows. Msys2 is one of them, and it includes the free compilers, and GFortran developers recommend it for Windows users.

Here is a procedure for the installation of Msys2 as of January 2020.

Msys2 and Mingw-w64

Installation

Step 1: Visit the official GFortran Wiki to find the link to Msys2 website. It shows a link to Mingw-w64, the name of the project that develops MSYS2. Go to the Mingw-w64 web page.

GFortran Wiki

Step 2: Visit the Mingw-w64 project site, and you find the “Download” link. Go to “Download”.

Mingw-w64 project website

Step 3: This page shows all the packages that this project maintains. Choose Msys2.

Msys2 link

Step 4: The page shows a link to Msys2 website in Github. Go to the website.

Link to Msys2 project website

Step 5: Get Msys2 installer on this website. Download a file with msys2-x86_64-xxxxxxxx.exe (xxxxxxxx is replaced with the date which is released). If you know your system is 32bit, download msys2-i686-xxxxxxxx.exe.

Msys2 installer website

Step 6: Run the installer and follow the instruction to set up the program.

Msys2 installer

Step 7: Invoke Msys2 window. The program runs automatically for the first time. After that, you can run it from the menu. Choose MSYS2 MinGW 64-bit (32-bit if needed).

Msys2 in the menu

Step 8: Make sure that you see a Msys window.

Msys2 window

Step 9: Msys2 consists of many dependent programs. Each program is prepared as a package. If the package is modified, you can download it through the internet. This process is automated by a command pacman.

For the first time, you have to date the built-in packages through the internet. In the Msys2 windows, type the following command.

pacman -Syu

It will ask you whether you allow downloading the updated packages. You can type y for yes. If it fails, close the window and try again.

Step 10: GFortran is also provided as a package. Type the following command in the window to install GFortran.

pacman -Su gcc-fortran

As above, it will ask you if you want to install the package. Type y, and wait for a while to finish the installation. After this step, you can use GFortran in this window.

You can confirm the successful installation with the following command.

gfortran

Directory structure

The Msys2 window runs Bash, and you can use most Linux commands in the window. Also, when you create some files, you can access the files with Windows Explorer.

The home directory is somewhere on your computer. You can access the drive C, use /c/. For example, the real home directory in Windows is /c/Users/your_name if your account name is your_name. Using this rule, you can change the directory to Documents, type cd /c/Users/your_name/Documents.

Back to index.html.

gfortran binaries for Windows

Stand-alone gfortran binaries for Windows are available as an installer. Download the installer, and run it (accept the GNU Public License, choose an directory to install gfortran, and let it work for you!). The installer sets your PATH environment variable, so that simply typing gfortran in a command prompt will run the compiler.

Please report any bugs to the fortran@gcc.gnu.org mailing-list.

See Windows for general GCC on Windows information.

Troubleshooting

I installed gfortran, and now what?

gfortran is now available from command-line. To open a command prompt, click on Start menu, choose Accessories and then Command Prompt, or choose Run and type «cmd». In the black window that opens, you can use gfortran to compile your Fortran code (assuming your program is file code.f95 in the current directory): gfortran code.f95 -o code.exe This creates an executable named code.exe.

When I type try to run gfortran, windows says «command not found»

The installer tries to add the gfortran program to your PATH environment variable, telling Windows where to look when you call for gfortran For this to work, the command prompt window must be openedafter the installation is complete Open a new prompt window, and try again!

I opened a new command prompt, after the installation completed, and it still says «command not found»

Check that you have indeed files in the directory you selected for installation (if you chose c:gfortran as installation directory, you should have directories like c:gfortranbin c:gfortraninclude … you should also have a file gfortran.exe in c:gfortranbin .

Now we have to tell Windows to look in c:gfortranbin for the compiler. Right click on My Computer, Properties, Advanced Tab, Environment Variables.

In the top section labeled «User variables for…» there may or may not be an entry called PATH. If there is, click on it, click edit, then add the following at the end of the line.

;c:gfortranbin

If there is not, click add.

Variable Name: PATH
Variable Value: c:gfortranbin

Click okay enough times to get back to the desktop, and open a new command prompt. You can do this by either going to Start, Accessories, Command Prompt, or by clicking run, and typing in cmd .

FORTRAN is a powerful programming language that is often over-shadowed by the more popular mainstream programming languages. Setting up and using FORTRAN on Windows 10 using the GCC Installation Manager makes the process quick and easy.

Visit mingw.org using your favourite browser and click on the downloads tab. Then click on the mingw-get-setup.exe link as pictured below.

Save the file to your downloads directory and run the program when the download completes. The MinGW Installation Manager will appear from which you can choose the packages to be installed. Note that the MinGW Installation Manager is a separate “app” that can be run at any time to manage or change the installed packages.

The various packages available through the Basic Setup are pictured below and include The GNU Ada Compiler, the GNU FORTRAN Compiler, The GNU C++ Compiler, and The GNU Objective-C Compiler.

Click on the All Packages option to reveal a host of other packages that are available.

We installed all of the available compilers, including the GNU FORTRAN compiler.

Testing the Installation (gfortran)

Create a simple test program as shown below using an editor (Visual Studio Code) and save it as addNumbers.f90 (Note that you must use a file extension such as .f90 or .f95 or the program may not compile).

program addNumbers

! This simple program adds two numbers
    implicit none

! Type declarations
    real :: a, b, result

! Executable statements
    a = 12.0
    b = 15.0
    result = a + b
    print *, 'The total is ', result

end program addNumbers

Open a terminal (cmd.exe) session and compile the program by entering the following command: gfortran -c addNumbers.f90

Enter the following command to generate an executable file: gfortran -o addNumbers.exe addNumbers.f90

The program will compile to create the addNumbers.exe executable file. Type .addNumbers at the prompt to run the file from the current location as Windows Powershell will not load commands from the current location by default.

The program and terminal session from Visual Studio Code are as pictured below:

FTN95 from Silverfrost Limited is a complete Fortran development environment and includes the powerful Plato IDE. Version 8.70 was just released as discussed in our recently published article “New Release of FTN95 Version 8.70.”

Related Articles and Resources

  • The GCC Compiler Collection: gcc.gnu.org
    • GCC Binaries: gcc.gnu.org/install/binaries.html
      • GCC For Windows 64 and 32 bits: mingw-w64.org/doku.php
  • MinGW – Compiler Suite (http://mingw.org)
  • GNU Fortran: Using the Compiler (https://gcc.gnu.org/wiki/GFortranUsage)
  • Fortran – (2018, August 26). Wikibooks, The Free Textbook Project. Retrieved 19:38, January 4, 2020, from https://en.wikibooks.org/w/index.php?title=Fortran&oldid=3454070.
  • Fortran 90/95 Programming Manual (fifth revision 2005)
  • Free Fortran Compilers (https://www.thefreecountry.com/compilers/fortran.shtml)
  • Absoft – Absoft Pro Fortran – Paid license required.
  • Simply Fortran – simplyfortran.com, version 3.7 as of this writing (Approximatrix) – Windows, MacOS, GNU/Linux. Free 30-day trial. NOTE: Use Google’s CHROME browser to download this package on Windows 10. Microsoft’s EDGE browser terminates the download prematurely.
  • Lahey/GNU Fortran – Free trial versions are available for download.
    • Lahey Fortran Professional (32-64 bit)
    • Lahey/GNU Fortran – Rainier edition (32-64 bit)
    • Lahey/Fujitsu Fortran Express (32 bit)
  • Introduction to Programming Using Fortran 95 (fortrantutorial.com)
    • SilverFrost FTN95 Personal Edition (SilverFrost.com)
  • JDOODLE – Online Fortran Compiler IDE
  • Fortran Tutorial – https://www.fortrantutorial.com/
  • SilverFrost FTN95 – Personal Edition is free for home use or evaluation purposes only. Tiered licensing is available for commercial or academic purposes.
    • The free personal edition will display a splash window as shown below:
  • Winteracter – The Fortran GUI Toolset (Interactive Software Services Ltd – UK)
  • Gino – Graphics and GUI solutions for Fortran and C under Windows and Linux. (Bradly Associates).

Как заставить работать программу на Фортране 77 в Windows 10 x64 ? Программа отлично работала в ХР. Теперь у меня Windows 10, а среда Microsoft Developer, в которой работал компилятор и сама программа, несовместима с этой ОС. С Visual Studio предлагается Фортран 90, но, во-первых, переписывать всю программу (очень большая!) никому не пожелаю, но, главное, предложенная в качестве теста программка, не прошла отладку.

Код из файла «Помощи» при Silverfrost FTN95:

Fortran
1
2
3
4
5
6
7
8
PROGRAM Test1
  INTEGER i
  REAL::x=0.0
  DO i=1,10
    PRINT*,x,x*x
    x=x+0.25          
  ENDDO
END PROGRAM Test1

Результат компиляции:
Build started: Project: Test1, Configuration: Debug .NET ——
Building project Test1…
Updating References…
Linking…

ЌҐ®Ўа Ў®в **®Ґ ЁбЄ«озҐ*ЁҐ: System.TypeInitializationException: €*ЁжЁ «Ё§ в®а вЁЇ «Salford.Linker» ўл¤ « ЁбЄ«озҐ*ЁҐ. —> System.TypeInitializationException: €*ЁжЁ «Ё§ в®а вЁЇ «Salford.Fortran.RTLibrary» ўл¤ « ЁбЄ«озҐ*ЁҐ. —> System.TypeInitializationException: €*ЁжЁ «Ё§ в®а вЁЇ «Salford.Fortran.RTLibrary1» ўл¤ « ЁбЄ«озҐ*ЁҐ. —> System.AccessViolationException: Џ®ЇлвЄ звҐ*Ёп Ё«Ё § ЇЁбЁ ў § йЁйҐ**го Ї ¬пвм. ќв® з бв® бўЁ¤ҐвҐ«мбвўгҐв ® ⮬, зв® ¤агЈ п Ї ¬пвм Ї®ўаҐ¦¤Ґ* .
ў Salford.Fortran.RTLibrary1..cctor()
— Љ®*Ґж ва ббЁа®ўЄЁ ў*гваҐ**ҐЈ® б⥪ ЁбЄ«озҐ*Ё© —
ў Salford.Fortran.RTLibrary1.__init_c_io()
ў Salford.Fortran.RTLibrary.InitLibrary()
ў Salford.Fortran.RTLibrary..cctor()
— Љ®*Ґж ва ббЁа®ўЄЁ ў*гваҐ**ҐЈ® б⥪ ЁбЄ«озҐ*Ё© —
ў Salford.Fortran.RTLibrary.InitLibrary()
ў Salford.Linker..cctor()
— Љ®*Ґж ва ббЁа®ўЄЁ ў*гваҐ**ҐЈ® б⥪ ЁбЄ«озҐ*Ё© —
ў Salford.Linker.Main(String[] args)

Build log saved at: «file://C:UsersAlexanderDocumentsSilverfrost FTN95 ExpressTest1Test1DebugNETbuildlog.txt»
Test1 build failed.
========== Build: 0 succeeded or up-to-date, 1 failed, 0 skipped ==========

Microsoft Delivery Studio несовместим с Windows 10. Visio Studio тоже не работает. Так как же добиться работы программы на Фортране?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

Содержание

  1. Fortran
  2. Возможности
  3. Интерфейс
  4. Fortran установить на windows 10
  5. Скачать Fortran 3.11
  6. Удобства использования программы «Fortran»:
  7. Программная оболочка софта «Fortran»:
  8. Основные характеристики программы «Fortran»:
  9. Fortran установить на windows 10
  10. GNU Fortran
  11. Похожие программы
  12. 11 комментариев для “GNU Fortran”

Fortran

fortran glavnaya

fortran proekt

Fortran — это одна из немногих действительно удобных сред разработки для одноименного языка. Вообще Фортран, нынче не особенно востребован, так что найти достойное программное решение для написания кода на нем, да еще и со встроенным дебаггером, довольно сложно. Так что адекватных альтернатив данному приложению не существует.

Возможности

Итак, пользуясь данным редактором кода вы сможете комфортно писать приложения на Fortran используя функции подсветки синтаксиса, дебаггинга и рефакторинга. При необходимости можно скрывать отдельные блоки с кодом, легко переключаться между файлами проекта и выполнять поиск нужных строк, переменных и выражений. Из функций, присущих абсолютно всем подобным редакторам, можно отметить быструю отмену внесенных изменений, поддержку вкладок и работу точками останова.

Из прочих преимуществ стоит выделить наличие системы всплывающих подсказок, которые отображаются при написании кода на Fortran. Программа может автоматически указывать на частые проблемы вроде зацикливающихся функций и ошибок в названиях команд/аргументов. Редактор отличное запускается под WINE на системах отличных от Windows и комплектуется подробной документации. Последняя, как и сама программа, доступна исключительно на английском языке. Впрочем, учитывая «специализацию» ПО данный факт сложно отнести к серьезным недостаткам.

Интерфейс

Основную площадь окна редактора, что вполне логично, занимает окно с кодом. Справа от него располагается древовидный список с файлами проекта, немного выше — панель с инструментами. При необходимости размер панелей можно изменять путем простым перетаскиванием за специальные маркеры, что очень удобно. Единственная серьезная проблема здешней графической оболочки заключается в том, что она ощутимо «лагает» на новых версиях Windows, выпущенных после «восьмерки».

Источник

Fortran установить на windows 10

I did not know the post by samy.m:

(1)Open the CD with explorer

(2) Go to folder x86

(3) execute the setup.exe located inside folder :: x86/setup.exe

(4) You can apply all updates as usual.

It works very well for me. Email me if you have any concerns.

In fact I did the same and the result was OK for my office computer
and I failed when I repeated the above procedure in my home computer.

Remarks:
My Comnpaq Fortran 6.1 is a Professional version which includes
IMSL library. I use fortran for more than forty years. I write
codes both
(a) for my research papers
and
(b) for showing my post graduate
students that fortran (especially Fortran 95) is the best
language as regards the applications in mechanical
engineering.

Needles to say that I use IMSL library frequently.

Originally I used Compaq Fortran in my home computer in
a virtual XP environment which is a part of (which can be installed under)
Windows 7. After upgrading to Windows 10 the virtual XP disappeared. Then
it occurred to me that CVF is in fact a 32 bit program system, and these
programs can be used, in general, in a 64 Windows environment. It (CVF) has
some advantages when compared to the later versions of the program:
simplicity as regards the installation and and it provides a more user
friendly environment.

In my office computer I first installed the program in HYPER-V environment,
which is not as friendly as the virtual XP environment under Windows 7. Then,
I do not know how and why. I made an attempt at running steupx86.exe and I succeeded.

Hence I have to installations of CVF in my office computer.

Let me say finally that I am not an expert, I am only a Fortran 95 user.

Источник

Скачать Fortran 3.11

rating offrating offrating offrating off rating off

«Fortran» — одна из немногих действительно полезных сред разработки для одноименного языка. В целом, программный софт «Fortran» в настоящее время не особо пользуется популярностью, поэтому найти хорошую программу для написания кода на нем и даже со встроенным «debagger» не просто. Поэтому альтернатив этому приложению недостаточно.

Удобства использования программы «Fortran»:

Таким образом, используя этот редактор кода, можно удобно писать приложения в Фортране, пользуясь опцией подсветки синтаксиса, рефакторинга и отлаживания. Из всех функций, характерных для таких редакторов, можно отметить быструю отмену внесенных вами изменений, поддержку вкладок и работу с точками. Если нужно, то можно скрыть некоторые блоки с кодами, легко переключаться между файлами проекта и искать нужные строки, переменные и выражения.

Одним из других преимуществ является выделение наличия системы всплывающих подсказок, отображаемой при написании кода в Фортране. Программа может автоматически отображать общие проблемы, такие как функции цикла и ошибки в именах команд/аргументов. Сам редактор неплохо работает под WINE в системах, отличных от Windows, и дополняется подробными документами. Во-вторых, как и сама программа, она доступна только на английском языке. Однако, учитывая даже этот факт, его трудно отнести к серьезным недостаткам.

Программная оболочка софта «Fortran»:

Вполне логично, что основное пространство окна редактора занято окном, содержащим код. Справа от него находится список с файлами разработки и панель инструментов чуть выше. При необходимости можно изменить размер панелей, перетащив их за специальные маркеры, что очень удобно. Единственная важная проблема с графической оболочкой здесь заключается в том, что она ощутимо «подтормаживает» в новых сборках ОС Windows, которые вышли после версии «8»

Основные характеристики программы «Fortran»:

с программой очень легко работать;

имеется инструментарий для рефакторинга и отлаживания;

можно настроить синтаксис;

он имеет чрезвычайно простой и интуитивно понятный интерфейс для масштабирования;

имеется очень подробная документация;

софт укажет на совершенные ошибки.

Перед тем как скачать Fortran бесплатно на русском языке, прочитайте характеристики софта и требования к вашему устройству.

Источник

Fortran установить на windows 10

This web page provides GNU Fortran, C and C++ for Windows for download. Equation Solution build the compiler.

Download self-extracting executable, and run the executable to install.

Releases Self-Extracting File Note
32-bit 64-bit
9.2.0 gcc-9.2.0-
32.exe
gcc-9.2.0-
64.exe
Including gdb;
make;
OpenMP;
jcl;
neuLoop;
laipe2
10.3.0 gcc-10.3.0-
32.exe
gcc-10.3.0-
64.exe
Including gdb;
make;
OpenMP;
jcl;
neuLoop;
laipe2
11.1.0 gcc-11.1.0-
32.exe
gcc-11.1.0-
64.exe
Including gdb;
make;
OpenMP;
jcl;
neuLoop;
laipe2

Snapshot, or so-called beta or experimental version, is updated on a weekly basis. But, Equation Solution make no guarantee of availability. Download self-extracting executables in the following, and run the excutable to install.

Источник

GNU Fortran

GNU Fortran – название компилятора языка программирования Фортран, входящего в коллекцию компиляторов GNU.

GNU Fortran заменил компилятор g77, разработку которого остановили после выхода GCC (GNU Compiler Collection) версии 4.0. Новый компилятор включает в себя поддержку Fortran 95 и совместим с большинством языковых расширений g77, что позволяет ему стать превосходной заменой старой версии компилятора.

Экспериментальная версия GNU Fortran включалась в версии GCC 4.0.x, но только с версии GCC 4.1 GNU Fortran можно назвать полноценным инструментом разработки.

Развитие этого компилятора продолжается совместно с остальными компонентами GCC. GNU Fortran был ответвлён от проекта g95 в январе 2003, который стартовал в начале 2000 года. Как утверждают разработчики GCC, эти две кодовые базы имеют слишком большие различия.

GNU Fortran1

Ссылки

Похожие программы

Apache Hadoop

GLEW1

Apache Spark 1

Oracle SQL Developer

Oracle SQL Developer

Beye

Contao1

Schemetos 1

Protocol Buffers1

MonoGame

ZuluGIS1

11 комментариев для “GNU Fortran”

Нужно попробовать загрузить программу.

Неужели это бесплатно?

нужен беспдатнвй фортран для виндовс-7

Fortran необходим для инженерных расчётов

Использование данного языка программирования дает хороший результат

Скачал я этот “бесплатный” gfortran. Итог – нормальная установка, но без запускающего файла. И как его запустить не представляю
Может у кого это прошло успешно подскажете? Очень признателен.

Гораздо лучше компиляторы Salford Fortran
ftn77pe
или
ftn95pe
бесплатные для некоммерческого использования
Откуда скачать кому надо найдет (погуглит)
А с GNU компиляторами вечные проблемы, то то не так, то этого не хватает. Из этого множества съедобен более-менее gfortran, но по сравнению с выше названными фигня.

Николай, про ftn сказать не могу, но gfortran это как то, о чем эта тема – очень хороший компилятор. Да и нет никаких проблем с GNU компиляторами, прекрасно они работают. Что касается Gfortran-a, то он предоставляет не только полноценный 95-й стандарт, но и многое из 2003-го и 2008-го, пополнения выходят с кажой новой версией, к примеру gfortran давно поддерживает ООП из 2003-го стандарта.

константин, – gfortran это не среда разработки, а только компилятор, прописывающийся с path, меню или “кнопки” вы и не видите. Поставьте к примеру редактор Geany и скажите ему путь до gfortran, тогда сможете писать код и компилировать его. Или можете написать в блокноте код программы и дать команду компиляции из терминала, но это не так удобно. Либо ставьтe Force2, там gfortran в комплексте со своей cредой разработки, но gfortran там более старый и нет возможности выбора кодировок (по крайней мере не нашел).

Источник

Prerequisites

The Fortran language track requires that you have the following software
installed on your system:

  • a modern Fortran compiler
  • the CMake cross-platform build system

Prerequisite: A Modern Fortran Compiler

This language track requires a compiler with Fortran
2003 support. All
major compilers released in the last few years should be compatible.

The following will describes installation of GNU
Fortran or GFortran. Other fortran
compilers are listed
here.
Intel Fortran is a
popular proprietary choice for high performance applications. Most
exercises will work with Intel Fortran, but are only tested with GNU
Fortran so your mileage may vary.

Prerequisite: CMake

CMake is an open source cross-platform build system that generates build
scripts for your native build system (make, Visual Studio, Xcode, etc.).
Exercism’s Fortran track uses CMake to give you a ready-made build that:

  • compiles the tests
  • compiles your solution
  • links the test executable
  • automatically runs the tests as part of every build
  • fails the build if the any tests fail

Using CMake allows exercism to provide a cross-platform build script that
can generate project files for integrated development environments like
Visual Studio and Xcode. This allows you to focus on the problem and
not worry about setting up a build for each exercise.

Getting a portable build isn’t easy and requires access to many kinds of
systems. If you encounter any problems with the supplied CMake recipe,
please report the issue so we can
improve the CMake support.

CMake 2.8.11 or later is required to use the provided build recipe.

Linux

Ubuntu 16.04 and later have compatible compilers in the package manager, so
installing the necessary compiler can be done with

sudo apt-get install gfortran cmake

For other distributions, you should be able to acquire the compiler through your
package manager.

MacOS

MacOS users can install GCC with Homebrew via

brew install gfortran cmake

Windows

With Windows there are a number of options:

  • Windows Subsystem for Linux
    (WSL)
  • Windows with MingW GNU Fortran
  • Windows with Visual Studio with NMake and Intel
    Fortran

Windows Subsystem for Linux (WSL)

Windows 10 introduces the Windows Subsystem for Linux
(WSL). If
you have Ubuntu 16.04 or later as the subsystem, open an Ubuntu Bash
shell and follow the Linux instructions.

Windows with MingW GNU Fortran

Windows users can get GNU Fortran through
MingW.
The easiest way is to first install chocolatey
and then open an administrator cmd shell and then run:

choco install mingw cmake

This will install MingW (GFortran and GCC) to C:toolsmingw64 and
CMake to C:Program FilesCMake. Then add the bin directories of
these installations to the PATH, ie.:

set PATH=%PATH%;C:toolsmingw64bin;C:Program FilesCMakebin

Windows with Visual Studio with NMake and Intel Fortran

See Intel Fortran

Intel Fortran

For Intel Fortran
you have to first initialize the fortran compiler. On windows with Intel
Fortran 2019 and Visual Studio 2017 the command line should be:

"c:Program Files (x86)IntelSWToolscompilers_and_libraries_2019windowsbinifortvars.bat" intel64 vs2017

This sources the paths for Intel Fortran and cmake should pick it up
correctly. Also, on Windows you should specify the cmake generator
NMake for a command line build, eg.

mkdir build
cd build
cmake -G"NMake Makefiles" ..
NMake
ctest -V

The commands above will create a build directory (not necessary, but
good practice) and build (NMake) the executables and test them (ctest).

For other versions of Intel Fortran you want to search your installation
for ifortvars.bat on windows and on linux/macOS ifortvars.sh.
Execute the script in a shell without options and a help will explain
which options you have. On Linux or MacOS the commands would be:

. /opt/intel/parallel_studio_xe_2016.1.056/compilers_and_libraries_2016/linux/bin/ifortvars.sh intel64
mkdir build
cd build
cmake ..
make
ctest -V

Download Simply Fortran for Apple macOS

Select Distribution:

Intel macOS

for macOS 12.0 or higher

Version: 3.21 Size: 121 MB

Build: 3595 MD5: 67359736a2dfabb6a8740d10472e4dce

Apple Silicon macOS (Experimental)

for macOS 12.0 or higher

Version: 3.21 Size: 135 MB

Build: 3594 MD5: 18f9c5ea41c0077e4fcc4dce8f629d1f

Intel Legacy macOS

for macOS 10.6.8 through 10.15

Version: 3.21 Size: 84 MB

Build: 3595 MD5: abbd9c54683dddedbe3af9110f7471df

Simply Fortran can be installed on any modern Mac system. The integrated development environment is shipped as a fully-functional thirty day trial version. Purchasing Simply Fortran will enable all features after the trial period in addition to supporting the ongoing development of Simply Fortran.

The installer includes everything you need to get started, and there’s nothing more to download!

Simply Fortran for macOS incorporates the following:

Please note that Simply Fortran does not require a network connection. It will only contact the License Server if the user has purchased a Site License.. Please see our Privacy Policy for more information.

Older Versions

Older releases of Simply Fortran are available here.

Источник

Intel® Fortran Compiler

Build applications that can scale for the future with optimized code designed for Intel® architecture.

A Tradition of Trusted Application Performance

The Intel® Fortran Compiler is built on a long history of generating optimized code that supports industry standards while taking advantage of built-in technology for Intel® Xeon® Scalable processors and Intel® Core™ processors. Staying aligned with Intel’s evolving and diverse architectures, the compiler now supports GPUs.

Standards: The Path Forward

There are two versions of this compiler.

Intel® Fortran Compiler(Beta): provides CPU and GPU offload support of GPUs

Intel® Fortran Compiler Classic: provides continuity with existing CPU-focused workflows

Both versions integrate seamlessly with popular third-party compilers, development environments, and operating systems.

Features

†Initial support available in Intel® Fortran Compiler(Beta)

Development Environment Flexibility

Use the compiler in command line or in a supported IDE:

Benchmarks

компилятор fortran для windows 10

Try in the Intel® DevCloud for Free

Develop, run, and optimize your code in this cloud-based development sandbox with 120 days of full access. Access samples or run your own workloads.

Access oneAPI Software

Use the Latest Intel® Hardware

Download the Toolkit

Intel® Fortran Compilers are included in the Intel® oneAPI HPC Toolkit. Get the toolkit to analyze, optimize, and deliver applications that scale.

Documentation

Specifications

Intel Fortran Compiler(Beta)

Host and target operating systems:

†† OpenMP host and offload support available only in Intel Fortran Compiler(Beta)

For more information, see the system requirements.

Intel Fortran Compiler Classic

Host and target operating systems:

†† OpenMP host support available only

For more information, see the system requirements.

Get the Single Component

A stand-alone version of this component is available.

Get Help

Your success is our success. Access these support resources when you need assistance.

For additional help, see our general oneAPI Support.

Related Products

The Intel® oneAPI DPC++/C++ Compiler is a standards-based, cross-architecture compiler that builds high-performance applications by generating optimized code for Intel® Xeon® Scalable processors, Intel® Core™ processors, and supported XPUs. It allows you to:

Customer Testimonials

«Intel Fortran Compiler outperforms GNU Fortran (GFortran) by more than 40 percent when testing various scenarios on the complex Stokes Inversion based on Response functions (SIR) numerical code on Ubuntu Linux*. Numerical results were identical between the two compilers, and saved me precious time and effort.»

— Carlos Quintero Noda, doctor of astrophysics; International Top Young Fellow, Japan Aerospace Exploration Agency (JAXA)

«Intel continues to impress me with its Intel Fortran Compiler. Having used various other Fortran compilers, and then switching to Intel® Parallel Studio XE thanks to the Intel® software academic offering, we saw immediate benefits. Our application involves a large number of scientific calculations and computations, and we saw additional performance gains with the Intel Fortran Compiler. The seamless integration of the Intel Fortran Compiler with Microsoft Visual Studio* is worth mentioning and appreciating.»

— Dan Geană, professor of Department of Applied Physical Chemistry and Electrochemistry, faculty of Applied Chemistry and Materials Science, University Politehnica of Bucharest

«I am using Intel Fortran Compiler to develop an automated forest cover identification system from digital aerial images forming stereo pairs. This system uses advanced texture and shape analysis to identify and classify the forest cover (species, density, and height) in order to produce forest inventory maps. Stereo matching is used to produce 3D digital canopy models that are subsequently analyzed by the texture and shape classification program. The advantages of Intel Fortran Compiler are:

— Jean Vezina, software developer and forest engineer

«I develop Fortran-based and Linux cluster-based applications and think [the] Intel® Parallel Studio XE Cluster Edition is a great productivity suite. It is full of very useful tools for developers of complex code who want outstanding application performance. The optimization reports from the Intel Fortran Compiler are extremely useful and take advantage of the explicit vectorization compiler features as much as possible. Intel® Math Kernel Library is a great collection of ready-to-use math libraries that speed development and application performance. Productive stuff for developers from Intel. Keep it coming!»

— Alexandre Silva Lopes, senior researcher, Centre for Wind Energy and Atmospheric Flows, University of Porto, Faculty of Engineering

«Intel has done a great job implementing OpenMP 4.0 in the Intel Fortran Compiler of Intel Parallel Studio XE. The standards support is also excellent. I have used OpenMP and the Intel Fortran Compiler in our scientific computing cluster at the University of Alcalá to add parallelism in the computation of an atmospheric radiative transfer calculation. We have reduced the time needed to analyze a scenario from two months to 12 days by implementing OpenMP with the Intel Fortran Compiler. My sincere advice is to try Intel Parallel Studio XE.»

— José Alberto Morales de los Ríos Pappa, electronics and software developer for the infrared (IR) camera in the Extreme Universe Space Observatory Onboard Japanese Experiment Module (JEM-EUSO) mission, Math and Physics Department, University of Alcalá

Источник

Installing GFortran

GFortran is the name of the GNU Fortran project. The main wiki page offers many helpful links about GFortran, as well as Fortran in general. In this guide, the installation process for GFortran on Windows, Linux, macOS and OpenBSD is presented in a beginner-friendly format based on the information from GFortranBinaries.

Three sources provide quick and easy way to install GFortran compiler on Windows:

In all the above choices, the process is straightforward—just download the installer and follow the installation wizard.

Unix-like development on Windows

For those familiar with a unix-like development environment, several emulation options are available on Windows each of which provide packages for gfortran:

All of the above approaches provide access to common shells such as bash and development tools including GNU coreutils, Make, CMake, autotools, git, grep, sed, awk, ssh, etc.

We recommend the WSL environment for those looking for a Unix-like development environment on Windows.

Linux

Debian-based (Debian, Ubuntu, Mint, etc…)

Check whether you have gfortran already installed

If nothing is returned then gfortran is not installed. To install gfortran type:

to check what version was installed type:

You can install multiple versions up to version 9 by typing the version number immediately after “gfortran”, e.g.:

To install the latest version 10 you need first to add / update the following repository and then install:

RPM-based (Red Hat Linux, CentOS, Fedora, openSuse, Mandrake Linux)

Since Fedora 22, dnf is the default package manager for Fedora:

Источник

Компилятор fortran для windows 10

This web page provides GNU Fortran, C and C++ for Windows for download. Equation Solution build the compiler.

Download self-extracting executable, and run the executable to install.

Releases Self-Extracting File Note
32-bit 64-bit
9.2.0 gcc-9.2.0-
32.exe
gcc-9.2.0-
64.exe
Including gdb;
make;
OpenMP;
jcl;
neuLoop;
laipe2
10.3.0 gcc-10.3.0-
32.exe
gcc-10.3.0-
64.exe
Including gdb;
make;
OpenMP;
jcl;
neuLoop;
laipe2
11.1.0 gcc-11.1.0-
32.exe
gcc-11.1.0-
64.exe
Including gdb;
make;
OpenMP;
jcl;
neuLoop;
laipe2

Snapshot, or so-called beta or experimental version, is updated on a weekly basis. But, Equation Solution make no guarantee of availability. Download self-extracting executables in the following, and run the excutable to install.

Источник

Блог F-SEPS

понедельник, 23 января 2017 г.

Ламповый теплый Fortran

Contents

Introduction

Инженер на любом языке программирования программирует на Fortran.

Это шутка, но, как обычно, только отчасти. 🙂

Fortran – старейший язык высокого уровня, задуманный изначально как FORmula TRANslator для ученых и инженеров. Fortran создавался в IBM начиная с 1954 года суровым чуваком Джоном Бэкусом.

компилятор fortran для windows 10

Формально первым языком высокого уровня считается Планкалкюль (1945), компилятор которого, правда, был создан только в 2000. Fortran в 1950-х был не просто изобретен (точнее – «интуитивно нащупан»), но сразу реализован. Он – первый «по-честноку».

Благодарные ученые и инженеры активно используют Fortran до сих пор, несмотря на очевидную его моральную устарелость. (Сейчас XXI век, четвертая пятилетка). Мы тоже не исключение. На Fortran меня подсадили в 2009 году седовласые профессора кафедры «Прикладная математика» петербургского Политеха, с которыми мы вместе создавали одну нетривиальную загогулину. С тех пор слезть с него не удается никак.

Причин продолжения использования Fortran несколько:

Огромная, накопленная за пол века база инженерно-научного кода.

Скорость. Программы на Fortran – очень быстрые. Компиляторы Fortran чрезвычайно эффективны, а используемые математические библиотеки алгоритмически отточены как лезвия бритв. Кроме того, современный Fortran очень эффективно позволяет распараллеливать вычисления.

Удобство работы с матрицами и вообще с математикой. В Си-подобных языках этого можно добиться только с помощью ряда библиотек, здесь – все «из коробки».

Он простой как топор и императивный как танк. Инженеру/ученому не надо забивать голову программистскими премудростями (объектно-ориентированными или функциональными парадигмами, либо особенностями распределения памяти, указателями и т.д., и т.п.). Можно просто писать свои сладкие формулы.

Он компилируемый. Программы очень просто кому-нибудь отдавать безо всяких ваших виртуальных машин.

Как ни странно, он развивается и поддерживается. Стандарты регулярно обновляются (последний – 2015), компиляторы – совершенствуются.

На самом деле, Fortran действительно хорош для задач вычислительной математики, требующих очень высокой скорости исполнения кода с одной стороны, а с другой стороны – не слишком сложных в плане организации данных. Большинство околонаучных задач таковы. Однако, если данных все-таки много (не по объему, а по запутанности), а проект – сложен, то Fortran с удовольствием поспособствует его превращению в летающего макаронного монстра.

Если высокая скорость не требуется, лучше взять более современный язык «сверхвысокого» уровня: Python с библиотеками NumPy и SciPy или специализированный математический язык Mathematica или MatLAB (или свободные аналоги; для последнего – Octave или SciLAB ). На них разработка «научного» проекта будет в разы быстрей и прозрачней, правда все будет работать чертовки по-черепашьи.

Часто проекты так и приходится создавать в два этапа:

Реализация на быстром Fortran (или С/С++ ).

Компиляторы Fortran

Живых компиляторов Fortran сегодня, как ни странно, не меньше десятка.

Установка GFortran в Windows

На январь 2017 последняя стабильная версия GCC с GFortran – 6.3, заканчивается работа над седьмой версией.

GFortran – разумеется, кроссплатформенный. Для Windows его можно получить и установить разными способами:

То же относится и к текущей версии 4.9 GFortran в CodeBlocs (он по сути там тот же самый из TDM-GCC ).

Надеюсь, это исправят. В остальном все работает как часы.

В дистрибутивах от Ляо этой проблемы нет.

Компиляция в GFortran

Из IDE

IDE для того и нужны, чтобы не думать, а нажимать кнопочки. 🙂 Все интуитивно понятно без дополнительных пояснений.

Из командной строки

Допустим, мы хотим запустить «чистый компилятор», не пользуясь IDE. Пишем программу в текстовом файле, например Hello.f08 :

Компилируем из командной строки:

Пример составлен так, чтобы смоделировать зависимости модулей друг от друга, показанные на схеме:

компилятор fortran для windows 10

Компилируется такой проект, чтобы не нарушался порядок зависимостей, следующим образом:

Компиляция с GNU Make

Инструкции компиляции пишутся в текстовом файле, который обычно называется Makefile (без расширения) и располагается в папке с исходниками.

NB! Строки, в которых записаны команды, должны начинаться с символа табуляции. Пробелы здесь ставить нельзя.

Простейший Makefile для программы из одного модуля Hello.f08 (наш первый пример) может выглядеть так:

Если из рабочего каталога вызвать

то мейк отработает первую цель, а именно – скомпилирует и запустит нашу программу. При этом файл Makefile подхватится по умолчанию. Первую цель, определенную в файле, можно вызывать еще проще, написав просто

Можно также указать требуемый мейк-файл явно, тогда он может называться как нам угодно:

В главной цели all перед командой запуска файла мы указали реквизит, одноименный с названием программы:

Make – как хороший солдат, любой ценой (но желательно наименьшей), должен выполнить поставленную перед ним цель. А заключается она в исполнении команд, при этом обязательным условием перед их исполнением является наличие реквизита. В качестве реквизита основной цели мы указали необходимость достижения «дочерней» цели, правило для которой описали так:

Цели, связанные с данными реквизитами, мы описали так:

Здесь находится перевод официальной справки по GNU Make.

Здесь – хороший материал «Эффективное использование GNU Make» от Владимира Игнатова.

Некоторые опции компилятора

О расширениях исходных файлов

Подключение математических библиотек к GFortran

BLAS и LAPACK

Как подключить BLAS и LAPACK к GFortran в Windows :

Протестируем. Решим систему линейных алгебраических уравнений (СЛАУ)

Наберем в файле test.f08 :

Компилируем, подключая библиотеки lapack / refblas :

Библиотеки дядюшки Ляо

В дистрибутиве GCC профессора Ляо (с сайта www.equation.com) имеются очень неплохие библиотеки:

NEOLOOP – для параллельных вычислений;

LAIPE2 – решение СЛАУ с матрицами коэффициентов различного вида, включая симметричные положительно определенные ленточные или просто разряженные, представляющие для нас особый интерес (почему – об этом потом). Решение выполняется с распараллеливанием процессов.

JCL – перенумерация строк и столбцов разряженных матриц для приведения их к ленточной форме.

Если нужно установить эти библиотеки в другие дистрибутивы, делаем следующее:

Компиляция программ с этими библиотеками выполняется с опциями:

(Первая разрешает доллар в именах функций как у него принято, остальные просто подключают библиотеки laipe2, neuloop4, jcl ).

Чтобы подпрограммы LAIPE2 заработали, надо предварительно вызвать процедуру laipe$use с указанием числа ядер процессора, которые вы хотите использовать (иначе не «заведется» – об этом Ляо забыл написать в справке).

Библиотеки NEOLOOP и LAIPE2 работают только на Windows 7 и более старших.

IDE и редакторы для GFortran

Для серьезной работы с языком хорошо иметь как IDE, со всем богатством возможностей, так и текстовый редактор (может быть, не один), позволяющий «что-нибудь сварганить» по-быстрому или подправить. Честно говоря, я IDE почему-то запускаю реже текстового редактора, с которым намного лучше постигается Дзен.

Какие есть варианты для GFortran в Windows?

IDE Code::Blocks

компилятор fortran для windows 10

На 64-разрядных машинах желательно поставить 64-разрядный компилятор GFortran (см. выше) и подключить его в качестве основного (все делается мышкой в настройках элементарно).

Вывод сообщений ваших программ не в консоль, в окно редактора (чтобы не было проблем с кодировками) можно сделать через меню Tools, создав новый инструмент, указав для него:

IDE Eclipse с расширением Photran

Eclipse – очень тяжелая штука. Я побаловался, но дальше она как-то не прижилась.

Прочие IDE

Текстовые редакторы

Не могу отделаться от ассоциации программистских текстовых редакторов с людьми разных возрастных групп. 🙂

Emacs и Vim

Седовласые старики. Очень опытные, мудрые и крутые, но найти с ними общий язык – очень сложно. Я пока не сумел, хотя пару десятков попыток делал. 🙂

Sublime Text, Atom, VS Code

Энергичные мужики. Моложавые, хипстерской внешности. На этих редакторах получается сделать «почти IDE».

Atom – открытый, мощный, но жирный и неторопливый. Использую его для некоторых других языков, Фортран как-то на нем не прижился.

Sublime Text – мой выбор. Мощный, быстрый, правда не открытый и не бесплатный (70 долларов, хотя незарегистрированной версией можно пользоваться сколько угодно).

компилятор fortran для windows 10

SciTE, NotePad++, AkelPad

Эдакие продвинутые юнцы. Меленькие, легкие, дерзкие, но далеко не такие мощные, как товарищи из первых двух групп. Не «почти IDE».

компилятор fortran для windows 10

С GFortran нетрудно настроить любой редактор. Привожу некоторые скриншоты работы приведенной выше программы по тестированию правильности установки LAPACK.

Литература по Fortran

Здесь – PDF-справка по GFortran. Очень неплоха. Коротко и по делу. Для работы нужен второй PDF по GCC в целом.

Здесь – очень хорошее краткое описание языка в стандарте 95 в википедии. Если вы пишете на других языках, прочитав это, станете гуру в Фортране за каких-нибудь пару часов. 🙂

Что прекрасно в Fortran

С матрицами (например, A, B, C) можно работать как с переменными:

К матрицам (поэлементно) могут быть применены любые чистые функции (как синус в примере).

Вырезки и сечения матриц:

С матрицами, вообще, множество удобных встроенных функций – практически на все случаи жизни.

Матрицы могут быть многомерными.

Вызов процедур: поддерживается перегрузка параметров, необязательные и именованные параметры.

Типы, включая комплексные числа. Удобные древовидные пользовательские типы (структуры данных).

Как ни странно, форматный ввод-вывод, к которому привыкаешь, но который я также отмечу как одно из самых ужасных свойств языка. 🙂

Что ужасно в Fortran

Современный Fortran позволяет писать более-менее сносный код, если не пользоваться устаревшими конструкциями языка, поддерживаемыми ради совместимости, например:

типизацией переменных по умолчанию на основе первых букв их имен;

разными точками входа в процедуры;

переходами goto с метками;

указателями и прочими средствами работы с памятью «напрямую» и т.д.

Не только эти, но и в принципе многие конструкции языка, конечно же, устарели. Что особенно бесит:

В Fortran нет строк переменной длины, размер строк нужно задавать явно.

Специфичны преобразования других типов данных в строку и обратно. Чтобы преобразовать, например, вещественное число r в строку str или наоборот, приходится делать это через операторы ввода-вывода:

Поскольку строки – фиксированной длины, которая обычно берется с запасом, даже при обычной конкатенации приходится строки обрезать по пробелам:

Разумеется, в Fortran нет никаких регулярных выражений и других «вкусностей», к которым в современных языках мы успели уже «прикипеть».

С другой стороны, если к этому попривыкнуть, печатать стройные красивые матрицы (а также засасывать их из текстовых файлов как исходные данные кодом в одну строку) – и в правду очень удобно.

Нет списков и вообще структур данных с изменяемой длиной «на лету». (Динамически размещаемые массивы, конечно же, есть).

Переусложненная система типов. Вещественные числа разной длины пишутся с указанием разновидности (KIND) весьма специфично:

С другой стороны, KIND можно определить на уровне директивы компилятора и везде использовать просто real и числа без этих « _8 »

Мало средств «декомпозиции и абстракции» для поддержания структуры больших проектов.

Избыточность языка, связанная с историей и совместимостью снизу вверх.

Наследуемый код, написанный за пол века «учеными и инженерами» – в подавляющей массе просто чудовищен. Чуть менее, чем весь созданный код. 🙂 Почему так – загадка. Прямой вины языка в этом нет. Потемки – душа ученого.

Вместо Conclusions

В этой импровизированной статье пока не был раскрыт ключевой вопрос абстракта «как заставить себя в XXI веке писать на Fortran?». 🙂

Мейнстримовый C++ предлагает аналогичную скорость.

Лаконичный Python предоставляет неслыханную мощь и ясность/читаемость кода. Одна строчка идет за 5-10 Фортрана.

На самом деле, у меня нет разумного ответа на сакраментальный вопрос, кроме лишь одного: Fortran надо любить. 🙂 Как дедушку и стареющего отца.

Каждый раз, открывая текстовый редактор с Фортраном, чувствуешь, что «подключаешься» к чему-то ретрофутуристично-прекрасному. 🙂 Будущее, как видели его в 60-х годах, космические полеты, покорение звезд. Элементарные частицы, атомные реакторы. Шуршащие пленкой вычислительные машины. Папиросы профессоров «Прикладной математики». Все это преломляется в вашем редакторе, хочется открывать его еще и еще. 🙂 А на современных машинах все эти отблески проносятся с бешенной скоростью… Ну и конечно, по совокупности качеств, с чего «статья» начиналась…

Пускай в этом блоге Fortran будет отправной точкой в мир более современных решений.

Источник

Понравилась статья? Поделить с друзьями:
  • Как установить gettext на windows 10
  • Как установить flprog на windows 10
  • Как установить get pip py на windows
  • Как установить flatout 2 на windows 10
  • Как установить geonics 2013 на windows 10 x64