Linking Fortran code with C in nvhpc (nvfortran and nvc)

I am trying to compile a code with Fortran and C with nvfortran and nvc.

For example this program

program hello
     print *, "Hello"
end program

Compiling this as nvfortran hello.f95 -o hello.x is ok.

But if when I try to compile with fortran and then linking with C

nvfortran -c hello.f95 -o hello.o
nvc -o hello.x hello.o -fortranlibs

I get

/usr/lib/x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'

Any suggestion?

*This works ok with gfortran and gcc

Given Fortran pre-dates C and Linux, it doesn’t have a “main” entry. Instead, we add a “f90main.o” during link which adds a “main” which in turn calls the entry point into the Fortran program. “f90main.o” also includes some initialization.

In general it’s best to link with Fortran compiler in this case, but if you add f90main.o, it should work.

% nvfortran -c test.f90
% nvc test.o -fortranlibs /opt/nvhpc/Linux_x86_64/22.7/compilers/lib/f90main.o
% a.out

Hope this helps,

Thanks Mat.
This helps a lot.

BTW, I had a similar solution.

I wrote a simple function in file called helper.c

#ifdef __PGI
int main(){
  return MAIN_();

Compiled as nvc -c helper.c then nvc test.o -fortranlibs helper.o