How to write a Fortran program that supports both static and dynamic memory management?
I'm working on a public 开发者_JAVA技巧release if a model using Fortran 9x and I'd like to design the code to support both static or dynamic memory management.
I've only seen one example of a code that supports something like this. It is implemented using preprocessors that look something like this:
The code would include some memory management control file with the following:
#ifdef STATIC
define NMEM_ N
define PTR_ # blank
#else
define NMEM_ :
define PTR_ ,pointer
The user supplies the following file to configure static memory:
#define N 100 # Example array size
#define STATIC
In the core code, you declare your variable as such:
real PTR_, dimension(NMEM_) :: x
Set STATIC during compilation, and it becomes
real, dimension(100) :: x
Unset STATIC (implicitly setting it to dynamic) and it becomes
real, pointer, dimension(:) :: x
and some later code allocates the memory.
This works perfectly fine, but I like to avoid using preprocessors if I can, and it does feel like a kludge to me. Is there a more standard solution to this problem, or is this how it is normally handled? Is there even much difference between static and dynamic compilations these days (keeping in mind that I will probably want to use as much memory as I can)?
Having both static and dynamic memory modes seems to me an unnecessary complication, making your code harder to read and having two paths, both of which have to be tested. It also creates more complicated instructions for the user, and a burden to follow when they "make" the program. I recommend just using dynamic allocation if the maximum array size isn't known at compile time. Furthermore, I recommend using allocatable arrays rather than pointers unless you need one of the few features that can only be achieved with pointers, such as arrays with non-unit strides. Allocatables are safer, with memory leaks essentially impossible. Fortran 95 compilers (dump any compiler than is only Fortran 90 at this point) have long supported dynamic memory allocation -- don't have any concerns about using it.
精彩评论