Black_Magic
Black_Magic

Reputation: 61

Separate CUDA compilation with CMAKE

I want to compile .cu and .cpp to .o files separately, then link them to executable. I have few simple files: cuda_func.cu. cuda_func.h and main.cpp. In main cpp I include cuda_func.h and run cuda_func(). I've come up with following cmake code:

project(cuda)

cmake_minimum_required(VERSION 2.8)

# CUDA PACKAGE
find_package(CUDA REQUIRED)
set(CUDA_SEPARABLE_COMPILATION ON)
set(CUDA_PROPAGATE_HOST_FLAGS OFF)
set(CUDA_HOST_COMPILER g++)

# COMPILE CU FILES
file(GLOB CUDA_FILES *.cu)
list( APPEND CUDA_NVCC_FLAGS "-gencode arch=compute_30,code=sm_30; -std=c++11")
CUDA_COMPILE(CU_O ${CUDA_FILES})

SET(CMAKE_EXE_LINKER_FLAGS  "-L/usr/local/cuda/lib -lcudart")

# SETUP FOR CPP FILES
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
include_directories(${CMAKE_CURRENT_SOURCE_DIR})

# COMPILE AND LINK
add_executable(main main.cpp ${CU_O})

But I get undefined reference to "cudaMemcpy" error. When I compile it by hand, using nvcc and g++ to get .o files and g++ finally to make executable it works fine. It seems like the cuda library isnt linked properly at the end. What should I do?

Upvotes: 1

Views: 2328

Answers (1)

AlbertM
AlbertM

Reputation: 1286

Cmake 3.8 added native support for CUDA (here is a document from NVIDIA that explains how to use it this way), you can simply add cuda as a language and the appropriate compiler will be used automatically for each file.

cmake_minimum_required (VERSION 3.8)

project(youProject LANGUAGES CXX CUDA)

add_executable(yourExecutable)
target_sources(yourExecutable <you can add c++ as well as cuda files here>)

// Or if you want to separate cuda and C++ more clearly, put your cuda code
// in a library and link to it (which obviously allows you to compile them separately)
add_library(yourCudaLib <you can add your cuda files here>)
target_link_libraries(yourProject PRIVATE yourCudaLib)

Upvotes: 2

Related Questions