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 cmain.cu.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:

[codebox]

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

LD_LIBRARY_PATH := /usr/local/cuda/lib64

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

CUDAFORTRAN_FLAGS := -L $(LD_LIBRARY_PATH) -I $(LD_INCLUDE_PATH) -lcudart -lcuda

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

cuda: pspline.cu

$(NVCC) -c pspline.cu $(NVCCFLAGS) $(PGPLOT_FLAGS)

plottest:

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

run:

./pspline

[/codebox]

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:

http://www.computationalmathematics.org/to…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.

MMB