gfortran w/ CUDA C How to link a gfortran w/ CUDA C

I’ve created a glue kernel routine in C that is callable from my gfortran module.

How do I link my gfortran objects w/ nvcc objects? Do I just compile them w/ gfortran (-c) and
then use

nvcc mykernel.c f1.o f2.o -o my_executable

I imagine there are library issues.

Anybody do this?

Vince Schuster

Use fortran to compile your fortran source code like this

gfortran -c fmain.f

then use gfortran linker to link your cuda binary files like this

gfortran -o test.exe fmain.o -lgcc -L/usr/local/cuda/lib64/ -lcuda -lcudart

The library path depends on your machine. Also you can use nvcc linker to do the same thing, but then you have to specify the Fortran library file.

Essentially you are doing it backwards.

Fist just compile your cuda code, “nvcc -c mykernel”

Also compile your fortran code with “gfortran -c myfortrancode”

Link all the object files together with gfortran, be sure to include a library path and include path to libcuda, and libcudart

Here is a Makefile that I have used to do this:


NVCC := /usr/local/cuda/bin/nvcc

LD_LIBRARY_PATH := /usr/local/cuda/lib64

LD_INCLUDE_PATH := /usr/local/cuda/include,/usr/local/pgplot


PGPLOT_FLAGS := -L/usr/local/pgplot -lcpgplot -lpgplot -lX11 -lgcc -lm

PGPLOT_DIR = /usr/local/pgplot/

NVCCFLAGS := -gencode arch=compute_20,code=sm_20 -I $(LD_INCLUDE_PATH)

all: cuda plottest run




 gfortran -o pspline pspline.o $(PGPLOT_FLAGS) $(CUDAFORTRAN_FLAGS)




You can do this with any fortran compiler, I’ve personally done it with both gfortran and ifort.

There is a very good guide here:…om_fortran.html

The technically sophisticated way to do this is use the iso_c_binding module in the Fortran compiler. It avoids the issues with name mangling and padding. It may have a somewhat longer learning curve, but for the long run is the better approach.