Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CUDA Separate compilation issues using cmake [duplicate]

Tags:

c++

cuda

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?

like image 738
Black_Magic Avatar asked Feb 16 '26 07:02

Black_Magic


1 Answers

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)
like image 109
AlbertM Avatar answered Feb 17 '26 21:02

AlbertM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!