Fortran & C 混编

C 调用 Fortran

 

c2ffn.f

 


 

      SUBROUTINE NAMEAGE(NAME, NLEN, AGE, TEMP)
      CHARACTER*(*) NAME
      INTEGER NLEN,AGE
      REAL TEMP
C
      WRITE(6,1000) NAME(1:NLEN),AGE,TEMP
 1000 FORMAT(1X,'Hello ',A,', who is ',I2,
     .       ' years old, has a temperature of ', f4.1)
      RETURN
      END

 


 

 

c2f.c

 

 


 

#include
#ifdef _CRAY
# include
#  define nameage       NAMEAGE
#else
#  if !defined(_AIX) && !defined(__hpux)
#    define nameage     nameage_
#  endif
#  define _fcd          char *
#  define _cptofcd(a, b)   (a)
#  define _fcdlen(a)    strlen(a)
#endif

void nameage(_fcd name, int *nlen, int *age, float *temp);

int main()
{
    char *name = "Knut";
    _fcd fp;
    int nlen, age = 4;
    float temp = 98.6;

    nlen = strlen(name);
    fp = _cptofcd(name, nlen);

    nameage(fp, &nlen, &age, &temp);
    system("pause");

    return 0;

}

 

 


 

 

Makefile

 


f77 = g77
 
#
tar = demo
 
#
src = c2f.c
 
#
srcf = c2ffn.f  
 
#
obj = $(src:.c=.o)
 
objf = $(srcf:.f=.o)
 
 
${tar} : ${obj} ${objf}
    ${f77} -o ${tar}  ${objf} ${obj} 
 
${obj} : ${src}
    ${CC} -c ${src} -o ${obj}
 
${objf} : ${srcf}
    ${f77} -c ${srcf} -o ${objf}
clean:
    rm -f  *.o


 

 

Fortran 调用 C

 

 


 

#include
#ifdef _CRAY
#  include
#  define nameage       NAMEAGE
#else
#  if !defined(_AIX) && !defined(__hpux)
#    define nameage     nameage_
#  endif
#  define _fcd          char *
#  define _fcdtocp(a)   (a)
#  define _fcdlen(a)    strlen(a)
#endif

void nameage(_fcd name, int *age, float *temp) {
        char *cp;
        size_t len;

        cp = _fcdtocp(name);    /* convert to C char* */
        len = _fcdlen(name);

        /* strip trailing blanks */
        while (cp[len-1] == ' ' || cp[len-1] == '/0') --len;
        printf("Hello %.*s, who is %d years old, "
               "has a temperature of %4.1f/n", len, cp, *age, *temp);
}

 


 

 

 

 


 

      PROGRAM F2C
C
      CHARACTER*32 NAME
      INTEGER AGE
      REAL TEMP
C
      NAME = "Knut"
C add null character at end for portable & safe handling by C
      NAME(LEN(NAME):LEN(NAME)) = CHAR(0)
C note that LEN(NAME) = 32 in this case
      AGE = 4
      TEMP = 98.6
      CALL NAMEAGE(NAME, AGE, TEMP)
      END

 


 

 

#
CC = gcc

f77 = g77

#
tar = demo

#
src = f2cfn.c

#
srcf = f2c.f

#
obj = $(src:.c=.o)

objf = $(srcf:.f=.o)


${tar} : ${obj} ${objf}
    ${f77} -o ${tar}  ${objf} ${obj}

${obj} : ${src}
    ${CC} -c ${src} -o ${obj}

${objf} : ${srcf}
    ${f77} -c ${srcf} -o ${objf}
clean:
    rm -f  *.o

你可能感兴趣的:(FORTRAN,C/C++,MinGW)