Automatically set -I and -L flags in gfortran

Dear all,

I would like to begin by apologizing for not using the correct terminologies for stuff as I am somewhat new and recently started to explore fortran in detail. I hope to learn a lot about it!

I am using a package called libgmxfort (GitHub - wesbarnett/libgmxfort: Modern Fortran toolkit for analyzing GROMACS simulations) to read XTC file. The only way my code compiles and runs satisfactorily is
gfortran readxtc.f90 -I ~/libgmxfort-master/build/include/ -L ~/libgmxfort-master/build/lib -lgmxfort
However, it is trouble to provide the paths to -I and -L everytime. Is there a way to have those paths always on as I believe it wont hurt if I include -I and -L but do not use the said package in the code.

Please suggest a way to have the two flags set automatically so that the code should just run like gfortran readxtc.f90 like any other normal code.

Thank you in so much in advance for your assistance.


There are a few ways to do this. One is to define a shell alias. However, you will find this to be a limited, and limiting, approach to the general problem. A more general approach is to learn how a build system works. There are several to choose from. The POSIX standard one is called make. There are online tutorials to get you started. It is powerful and flexible but quirky. With this approach, you will define a file called Makefile in the same directory as the source code. This file contains all of the dependencies and libraries. Then to compile the program, you would enter a command like



make programname

A good thing about this is that it documents the order that the files must be compiled, all of the compiler options, all of the libraries, and so on. So if other people need to compile and run the code, all of that is already set up, they do not need to rediscover all of those details. This general feature also applies to the other build systems that you might want to try.

might be a good place to start looking at build systems. Note that depending on the system you are on and the compiler and loader you are using (and the options you use) the LD_LIBRARY_PATH environment variable can be set to add a directory to the load path (like the -L switch) or can be added to /etc/ if you have root privileges and some compilers allow setting the include path as well, often using $CPATH and/or $FPATH variables for include files; but the make/xmake/cmake path suggested is far more flexible and capable.

So read the man-page for gfortran and ld as there are other interesting options there as well; and some discussion about settting default search paths; including some pathnames already being searched that you might want to place your libraries at when you install them.

1 Like

Thank you @urbanjost and @RonShepard for your suggestions.

I will take a look at make.