Simple setting in Windows

I am going back to Fortran since my university days (25 years ago or so). I am writing to ask about the best and simplest setting on Windows. These are my needs and requirements:

  • OS: Windows 10.
  • I am using VS Code.
  • I have installed gFortran within tdm-gcc.
  • I have installed several extensions, such as C/C++, Modern Fortran and Code Runner (as suggested in this video).
  • I am planning to write and compile a programme using functions and routines created by me (properly structured in modules).
  • This programme will also use functions and routines from preexisting packages. I mostly need:
    • Reading from and writing into TXT files.
    • Creating and working with (sparse) matrices.
    • Integrating (one-variable) functions (with maybe one of the limits being ±infinity).
    • Nonlinear optimisation.
    • Working with probability distributions (calculating probabilities).
  • No need for object-oriented programming and things like that.
  • I’d rather not use GIT or things like that.

I would like to work with Fortran in the most ‘transparent’ and R-ish way, meaning:

  • Being able to debug within VS Code.
  • Being able to call functions from the console or the terminal in order to test my functions.
  • A setting in order to not get stuck when using preexisting packages. I mean, a setting in VS Code such that everything that needs being compiled is compiled when executing/compiling/testing/debugging the main programme file.

How can I do this?

If I am not clear enough, please ask me and I’ll try to be clearer.

Thank you in advance!


EDIT

When I say I wolud like to work in an R-ish way, I know the difference between a compiled and an interpreted language. However, when I work with LaTeX, for instance, the editor/compiler/environment usually takes care of ‘joining’ all the third-party packages that I am using in my document. It also creates (in the background) all the intermediate files needed to create the final PDF document. This is what I am expecting to get when working in Fortran.

1 Like

I program mostly on unix/posix systems, so I can’t help with your general Windows questions. I just wanted to say that you might want to reconsider this one point. I have found version control systems to be very useful. Over the years, I’ve used RCS, CVS, SVN, and nowadays GIT. I’ve never been fluent with any of them, but they have been useful nonetheless.

4 Likes

Thank you. It is just that I didn’t need to use GIT when I programmed in other languages (R, C, SciLab…).

I am also programming on Windows. I tried different things using VSCode or Code::Blocks. At the end of the day I ended up using Visual Studio (not VSCode) with intel Fortran. Debugging, code navigation, intellisense… you should be able to use all this.
If you want to stick to VSCode you might consider this link

1 Like

Welcome to Fortran-lang @vicent. Most of the things you are mentioning in terms of a code editor are very doable within VSCode.
Install Modern Fortran (the pre-release version). This should give you access to syntax highlighting, linting, debugging, formatting and snippets. For more advanced tasks like hover signatures, autocompletions, peeking definitions, etc. you will be prompted to install fortls our language server.

fortls - Language Server settings

The installation process for fortls on Windows currently is a bit harder than it is for Linux/MacOS but in summary you:

  • need Python >= 3.8
  • and if the location where pip installs packages is not in your PATH then you will have to explicitly set the location of the fortls.exe in VSCode like so (your path will be different):
{
  "fortran.fortls.path": "C:\\Users\\gn\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python311\\Scripts\\fortls.exe"
}

The default settings works great for most people, but if you want to tinker have a look at the docs
https://fortls.fortran-lang.org/options.html

Linting

Linting is also available, it uses a compiler by default gfortran to check if source files contain valid syntax. Linting diagnostic results get triggered when you save a file.
There is a host of options available for linting that you can use to setup your project but in summary, you should point the linter to include all your sources and all their compiled artefacts (i.e. .mod files).
You can search through the other available options for linting under the linting section in the Modern Fortran settings withing VS Code.

Configuration and Compilation

Configuring and compiling your projects, especially when you use third party libraries can be accomplished CMake; VS Code has a very good set of extensions for easy integration CMake Tools. That being said, how you compile your code is a developer choice and not related to the editor

If you don’t want use something like CMake, for small projects you can get away with using VS Code Tasks and compiling all the sources in a single command (be careful to do it in the correct order!)

These are essentially automatic scripts that you can use to invoke the compiler directly with your chosen source files

This is a simple task that compiles the Fortran source, currently in focus in VS Code.

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Compile Fortran",
            "type": "shell",
            "command": "gfortran.exe",
            "args": [
                "-g",
                "-Wall",
                "${file}",
                "-o${fileDirname}/${fileBasenameNoExtension}.o"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "problemMatcher": []
        }
    ]
}

(I think this is what pretty much CodeRunner the VS Code extension does, although I never had the need to use it.)

Using tasks, you can also make use of our own fpm - Fortran Package Manager which will compile your code and can easily fetch dependencies.

Debugging

On Windows debugging within VS Code only works with gfortran and GDB (no Intel compilers).
Since you will be using gfortran that should not matter.
Like all other debugging in VS Code you need to define a configuration in the launch.json file.

The one posted below uses the previous task (Compile Fortran) to first compile the source code and then launch it in Debug mode.

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "(gdb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}.o",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "Compile Fortran"
        }
    ]
}

There is an interactive element to the Debug console, but it is limited to what GDB and all other C/C++/Fortran debuggers I know off permit, so you probably won’t be able to compute function values on the fly like in Python or R whilst paused at a breaking point.

Summary

You can use Modern Fortran for VS Code on Windows as long as you use gfortran. However, you will need to make a decision on how to configure and compile your project (like in C and C++). CMake is a great choice but can be slightly intimidating at first glance, fpm is substantially easier to use but it is also less feature-rich.

fpm can come close to this but in general C, C++ and Fortran don’t work this way.

2 Likes

Visual Studio Community Edition with Intel fortran compiler through Intel OneAPI. This is the only pure windows solution. Everything else uses command line for compilation and linking like linux.

1 Like

That it is simply incorrect.

A quick Google search shows that VS uses by default msbuild which is a build system with a command line tool. Not only that but Intel Fortran in VS is incompatible with msbuild so you have to use devenv to use the Intel Fortran build system, another command line tool.

If what you are referring to is the GUI experience of compiling from within the editor with the press of a button that is also not unique to VS. VS Code (and I’m sure many other editors/IDEs) have plugins (in VS Code’s case many made and maintained by Microsoft) that allow that. I mentioned CMake Tools in my previous answer, but there is Makefile Tools and Meson

That being said, VS is a full fledged IDE, a commercial product and the only program that offers complete integration with Intel Fortran. So if one wants to use Intel Fortran compilers, for now at least, go with VS.

1 Like

Version control is an affordable and yet powerful tool to travel back in time, to test out multiple concepts in parallel, to provide a safety net to identify the last version of source code where feature xyz still was functional (by bisection in commit history), … just to mention a few benefits to (re)consider. It already is helpful if you work on your own, and even more if you enter a collaboration. While initially designed for source code, it is extensible to anything «text like»* – including (because you mention it) LaTeX. See CTAN’s relevant entries in the topic cloud and support by dedicated editors like TeXStudio (for instance when writing a thesis).

Because you mention Windows as (principal) operating system accessible to you, possibly tortoisegit nesting into the pull-down entries of the Windows Explorer can serve you as point of entry for version control in general. By default, the setup runs in a way to be compatible to Linux/Unix and hence platforms like GitHub, GitLab, etc to ease future optional collaborations. The corresponding commands to the CLI may be learned one at a time (e.g., software carpentry, or learnxinyminutes).

(The analogue tortoisesvn for SVN/subversion requires contact to the «central server» for each checkout and commit. By today, I perceive this star-shaped design less flexible than the decentralized one used by git and hence moved most of my svn repositories to git.)

* If it comes to binaries (images in .png format, etc), the addition of git-lfs to git is more suitable.

Thank you all for your (very complete) answers.

To answer @gnikit (and all), I actually wouldn’t mind having to use some command-line instructions to make everything work (assuming that this can be done within VS Code) as long as the procedure is smooth. This is what I mean:

When I need to use third-party libraries/packages, I want the procedure to use them to be easy and clear. Ideally, the sentences to be written on the command line, or whatever it may be, should always be the same. I want to avoid troubles such as spending, say, one day figuring out how to ‘include’ or linking an outer package and making it actually work within my project. [For sure, I’ll have to read the documentation of the package in order to know how to properly call or use its functions and procedures in my code, but I was not referring to this but to the step of actually making everything work.]

I’ll have a look at the solutions you all suggested to my question. Anyway, any other hint will be welcomed.

I have some second questions, related to/branching from the current one:

  1. Where can I read about the intermediate files that are created from the source file .F90 to build the final .EXE file, assuming that there are several module files and third-party packages being involved in the project?

  2. Related to the previous question, where can I read about the process of compiling a programme in Fortran?

  3. In Fortran, when you want to use some third-party packages, do you usually compile them from their Fortran source files, or are they instead usually distributed and used in a (pre)compiled form?

I hope these questions don’t seem too naïve to you.

Thank you in advance.

The site of Fortran-lang is a good place to start.
Building program

Fortran dependencies are usually distributed as source code. Problem is that intermediate mod files and static libraries are compiler specific (sometimes even version specific). If you are lucky the dependencies are available as fpm packages. It’s both a build system and a package manager that will make your life easier: fpm. Just get familiar with the toml manifest and voilà.
For building, alternative are either to use make files (or others) or visual studio to resolve the build dependencies (you might be eligible for a free community edition).
On windows, you could also try to link to dynamic libraries (aka DLL) but you almost never find precompiled DLL so you will have to compile these yourself anyway.
Good luck

1 Like

There is not much to read on this (as an applications dev). Fortran specific intermediate files like .mod and .smod are created by the compiler to speed up compilation (among other things). IMO the only thing that you need to know is that, like static and shared libraries, for your application to compile and link successfully these files need to have been generated by the same version of the compiler (same applies to linking and linkers). This is pretty much inline with C and C++.

As @davidpfister mentioned we have some introductory material here at Fortran-lang

In terms of specific compiler options to use, for that the safest place is to consult your compiler’s documentation. You mentioned GFortran so here is their relevant doc section

It depends, on the third-party package and where it is to be deployed (e.g. PC, workstation or cluster). Some third-party libraries like the implementations of MPI are usually pre-compiled in systems, so you have to be careful to use the same compiler version as the one that complied them. Other libraries like stdlib will probably need to be compiled from source. There is a lengthy discussion to be had here, but my very summarised opinion is that dependencies you can afford to compile from source, you should be doing so.

CMake has a pretty robust and mature way of finding (find_package) and downloading-configuring-compiling (FetchContent and ExternalProject) third-party packages.

fpm, is our build tool and a package manager, and is great too (although I am biased). It is meant to be an easy to use alternative to what currently exists. Integrating with fpm other projects is basically trivial, you can have a look at the Tutorials in the fpm documentation page for more

https://fpm.fortran-lang.org/tutorial/index.html

1 Like

Thank you all for your answers.

This really helped. The process of compiling is clearer to me now, which doesn’t mean that I think it is easy at all.

I started reading the tutorial about the FPM. I still have some questions:

  1. All the ‘hard work’ to build a programme is replaced and concentrated in the fpm.toml file, isn’t it?

  2. Still, I am not sure if I got it: In the example in which stdlib is included in the dependencies table, is the FPM expected to ‘search’ for the stdlib package in a sort of standard or default package repository, or is it instead going to search for stdlib somewhere in my hard drive??

  3. Just to be sure: Creating a new project with fpm new “creates a git repository with a dummy project in the fpm standard layout” (see here). This doesn’t mean that I have to use GIT, right? I guess that it is just the standard layout that GIT would need, in case I used GIT.

  4. I read that the FPM is still a work in progress. What risks or disadvantages can I expect if I decide to use it? I am planing to use packages related to

    1. reading from and writing into TXT files,
    2. creating and working with (sparse) matrices,
    3. integrating (one-variable) functions (with maybe one of the limits being ±infinity),
    4. nonlinear optimisation (both with and without derivatives), and
    5. working with probability distributions (calculating probabilities).

I am really looking forward to your answers. THANK YOU in advance!!

GIT is not a necessity, it is just a (very) good practice, but for any practical purpose you can forget about it for the moment… many have already stressed how useful it can be, using a version control is really a time saver and you can use git locally for even your smallest projects.

There is not much risk really, if you start with fpm it will propose you a layout that will work from the start, but nothing is stopping you from mixing other build systems in parallel if the need arises. Also, you will see that there are more and more Fortran packages/projects that are being uploaded with fpm compatibility. This means that if your project can be build with fpm, adding those as dependencies will be very easy.

The current point which I personally do not like much about managing dependencies with fpm, is that if you define the dependency to be an url from say a github or gilab project, it will download it and put it within build/dependencies folder. I would prefer that the packages were put in a folder parallel to the current project. But you can achieve that by 1. Manually download the package(s) 2. Use a path instead of an url to indicate the location of that package

1 Like

Wishing you great experiences. Patrick.

For IO you might take a look at io – Fortran-lang/stdlib to see if something fits your needs, there are also packages to manage JSON format which is also an ASCII file format GitHub - jacobwilliams/json-fortran: A Modern Fortran JSON API

For sparse matrices I have personally put a package which currently aims at proposing a memory layout for different sparse types, and get feedback from the community to improve it GitHub - jalvesz/FSPARSE: A Modern Fortran sparse matrices gallery, but there are many more solutions depending on your needs

For integration maybe this will help you quadrature – Fortran-lang/stdlib

For non-linear optimization you might want to take a look at GitHub - fortran-lang/minpack: Modernized Minpack: for solving nonlinear equations and nonlinear least squares problems or GitHub - jacobwilliams/slsqp: Modern Fortran Edition of the SLSQP Optimizer or prima/fortran at main · libprima/prima · GitHub

Others here in the forum might point you to other packages of interest to you :slight_smile:

1 Like

All the “hard work” is in fpm, the fpm.toml file only specifies special configurations for your project (if necessary) and dependencies.

fpm does not do any “searching” (at the moment). You either specify exactly where the git repository for the dependency exists (i.e. proj = {git = "https://..."}, where exactly on your machine it exists (i.e. proj = {path = "/path/to/proj"}, or it is a “special” dependency that fpm knows about (i.e. stdlib = *).

You do not have to use git. But in any case, git does not care at all about the organization of the files it helps you keep the history of.

While fpm is still a “work in progress”, I’d say it’s clearly self-sustaining now, and there is little risk of it going unsupported in the foreseeable future. The main disadvantage is that there is no way of specifying build steps beyond “feed the source files to the compiler”. I’ve found I can do without that feature in nearly all cases though.

I believe you should be able to find libraries supporting fpm in all of those categories, some of which others have already begun suggesting to you.

Good luck.

2 Likes