CUDA compilation on Linux (Makefiles)

I have been struggling with compiling complex CUDA code, with complex I mean a lot of .cu .F .cpp and .c files. I have created a makefile that can help you compile that kind of code. I'll try to give a quick view of it here explaining some parts:

First you'll need to specify the CUDA path and the compilers and linkers. Here I am using gcc and g++ for .c and .cpp files and nvcc for .cu files:

CUDA_INSTALL_PATH ?= /usr/local/cuda

CXX := g++
CC := gcc
LINK := g++ -fPIC
NVCC := nvcc -ccbin /usr/bin

Then you need to specify where to locate the CUDA header files :

# Includes
INCLUDES = -I. -I$(CUDA_INSTALL_PATH)/include

# Common flags
COMMONFLAGS += $(INCLUDES)
NVCCFLAGS += $(COMMONFLAGS)
CXXFLAGS += $(COMMONFLAGS)
CFLAGS += $(COMMONFLAGS)


Then you specify where to locate the CUDA binaries for linking :

LIB_CUDA := -L$(CUDA_INSTALL_PATH)/lib -lcudart


Then you specify the object files that the executable depends on and the name of the executable flle:

OBJS = sample_cuda_objectfile.cu.o sample_cpp_objectfile.cpp.o
TARGET = exec
LINKLINE = $(LINK) -o $(TARGET) $(OBJS) $(LIB_CUDA)


Finally you specify the compilation rules. The following are generic rules so all you need to do is change the OBJS and TARGET variables for compilation:

.SUFFIXES: .c .cpp .cu .o


%.c.o: %.c
$(CC) $(CFLAGS) -c $< -o $@

%.cu.o: %.cu
$(NVCC) $(NVCCFLAGS) -c $< -o $@

%.cpp.o: %.cpp
$(CXX) $(CXXFLAGS) -c $< -o $@

$(TARGET): $(OBJS) Makefile
$(LINKLINE)

Comments

Popular posts from this blog

Sharing the Network: From Circuit Switching to Packet Switching (The Hitchhiker's Guide to Computer Networks)

My PhD coping mechanism (or how speaking my mind out loud helps me maintain my sanity)

The Hitchhiker's Guide to Computer Networks