简体   繁体   中英

f2py with include files

I am compiling a fortran program called prog.f. It contains an include file called test.inc. This below runs successfully and shows that my include file is found. I have a prog.so file generated.

f2py -c prog.f -m prog

However when I call this module from python I get this error message:

Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import prog
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: ./prog.so: undefined symbol: unknown_function_

I suspect something to do with my compilation arguments but I am not too familiar with Fortran. Do I need to include my include file as well? If so how?

Yes, you need the include file. It might be something as simple as:

f2py -c include_file.f prog.f -m prog

although I haven't tested that. Alternatively, you might need to use the fortran include statement to include include_file into prog ... Also, if you're more familiar with C, virtually all fortran compilers that I know use the convention that prog.F is fortran code that should be preprocessed by cpp . So you could probably get your file included that way as well.

I also ran into this problem, and was able to find other discussions that simply stated that current f2py does not support preprocessing of files, such as #include statements and conditional compilation. https://groups.google.com/forum/#!topic/f2py-dev/aW65sEoSdG8

http://mail.scipy.org/pipermail/numpy-discussion/2009-November/046381.html

Two solutions: Simplest: If you are using gfortran to compile your code, rename any .f90 or .f file to .F90 or .F. Using a capital letter keys gfortran to automatically use the preprocessor (even if you don't specify).

Second: Use your Fortran compiler to preprocess the file and save the result as an intermediate Fortran code to be sent to f2py.

gfortran -E -D<Defines-for-compiler> file.f -cpp  -o outdir/file.f

where -E is the command to tell gfortran to just preprocess the file (may vary from compiler to compiler), and -D option to define any values to use during the preprocessing.

Saving the file to another directory (or changing the name completely) is necessary to avoid overwriting the original .f file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM