Iliketoproveit
Iliketoproveit

Reputation: 445

Using types defined in C header in Fortran

I am on a 64 bit machine runing RHEL 6.7 with gfortran 4.4.7.

I am trying to build a static library from a code base that looks like this

└── root
    ├── C_src
    │   └── foo.h
    ├── Fortran_src
        |──Makefile
        |── <other files>
        └── foo.f90

My Makefile simply lists all of the *.f90 files and makes .o files out of them.

When trying to build foo.f90 using the command

gfortran -c -I. foo.f90 -o

I get the following error

TYPE (MY_TYPE), INTENT (OUT) :: PassesOutput 
       1
Error: derived type 'mytype' at (1) is being used before it is defined

However after some digging I found that this type is being defined in foo.h

typedef struct{
    <bunch of stuff>
} MY_TYPE

Is there a way to build this code so that fortran is able to know about the type definition in foo.h when trying to compile foo.f90?

Upvotes: 0

Views: 166

Answers (1)

Marcus M&#252;ller
Marcus M&#252;ller

Reputation: 36352

C and Fortran are different languages. Though Fortran compilers typically support the C calling convention, that means that you can call C functions from fortran and the other way around. It doesn't mean the type information is parsed from the same syntax.

In other words: C headers are C headers, not fortran type definitions.

C simply has the ability to build types that Fortran can't have, and Fortran has types that C doesn't. So, there's no straight-forward translation between these worlds in general. If your C function takes a type that there's no direct equivalent for in fortran, you'll simply have a bad time.

So: nope, unless you have write some wrapper code, this won't work. There's automatic wrapper generators, but their complexity imho doesn't make sense in the use case you're describing. Seriously, if you can, avoid things like SWIG.

Upvotes: 2

Related Questions