Varargs support in calling C function

Tabbe 11-3 in User’s Guide (Calling Conventions Supported by the PGI Fortran Compilers) mentions varargs support for C convention. I’d like to know more details for this varargs support. Does this mean I can call a C function which has a varying number of args (like 2 args for this call and 5 args on another call)?

If you could have a small example on how to use this varargs option that would be of great help for me.

Compaq fortran also has !DEC Attributes varying:: name; does this correspond to varargs in Convention C mentioned here?

I use PGI Version 7.0-4 for Win32 (WinXP pro).

Thanks a lot

Giang Nong

Hi Giang Nong,

This support allows you to call, from Fortran, a C function that uses varargs. Below is an example of a Fortran program calling the C “printf” routine which uses varargs.

PGI$ cat printf.f90
program test_printf
!MS$ATTRIBUTES C :: printf
integer :: i, j
i = 10
j = 100

call printf("Hello World\n"//char(0))
call printf("I=%d\n"//char(0), %VAL(i))
call printf("I=%d J=%d\n"//char(0), %VAL(i), %VAL(j))

end program test_printf
PGI$ pgf90 printf.f90
PGI$ printf.exe
Hello World
I=10
I=10 J=100
PGI$

Note the use of “%VAL()” to pass variables by value, the concatenation of a NULL character to the end of strings, as well as declaring “printf” as a C function using the attributes directive.

Hope this helps,
Mat

Hi Mat,

Thanks a lot for the example. I still have two “minor” follow-up questions

1/ Is it necessary to declare external printf ? When do I need to declare external for a C routine and when it is not? Is it because Printf is a C intrinsic function so we don’t have to declare external. If I use a user-supplied C function I may need to declare it external?

2/ I ran the example in Visual Studio 2005 and got the results as follws:

Hello World\n
I=10\n
I=10 J=100\n

the new line"\n" seems not interpreted correctly. Do you know why?

Thanks again

Giang

Hi Giang,

Although not required, it’s always a good idea to explicitly declare subroutines as external. For functions (those that have a return values), you should explicitly declare the return type making sure that the C data type matches the Fortran data type (i.e int=>INTEGER4, float=>REAL4, etc.).

As for the extra newline characters, I’m not able to recreate this issue here. What steps did you do to get these results?

  • Mat