How to link CUDA dynamic libraries using CMake

Hello, everyone! I want to know how to use CMake to dynamically link CUDA libraries, I know it seems to require some extra restrictions, but don’t know exactly how to do it. Here is a simple example I wrote to illustrate my problem.

Directory structure:

Dir/
├── CMakeLists.txt
├── header.cuh
├── kernel.cu
└── main.cpp

Environment:

  • OS: Windows 11
  • GPU: RTX 3060 laptop
  • CUDA Toolkit: 11.6
  • Platform: Visual Studio 2022

header.cuh:

#include "stdio.h"
#include "cuda_runtime.h"
#include "device_launch_parameters.h"

extern "C" void f();

kernel.cu:

#include "header.cuh"

void __global__ print()
{
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    printf("%d\n", idx);
}

void f()
{
    print<<<1, 10>>>();
}

main.cpp:

#include "header.cuh"

extern "C" void f();

int main()
{
    f();
    return 0;
}

CMakeLists.txt:

cmake_minimum_required(VERSION 3.17)
project(test)
set(CMAKE_CXX_STANDARD 17)

find_package(CUDA REQUIRED)
enable_language("CUDA")
set(CMAKE_CUDA_STANDARD 14)
set(CUDA_SEPARABLE_COMPILATION ON)

string(APPEND CMAKE_CUDA_FLAGS " -rdc=true --cudart shared")

add_library(CUDA_COMP SHARED header.cuh kernel.cu)
set_property(TARGET CUDA_COMP PROPERTY CUDA_ARCHITECTURES 86-real 86-virtual)

add_executable(main main.cpp)

target_link_libraries(main CUDA_COMP)

The project can be configured successfully, but a problem with unresolved external symbols occurs when building the solution, as shown in the figure below.

There will be no problem if CUDA_ COMP is changed to a static library and linked, i.e. the word “SHARED” in line 12 of CMakeLists.txt is replaced with “STATIC”.

I also looked up the corresponding solution on Stackoverflow, but it didn’t work. For example, an answer on Stackoverflow mentioned adding " -rdc=true --cudart shared" to cmake, and I did the same (see line 10 of CMakeLists.txt).
This problem has been bothering me for a long time. I hope you can tell me the cause of the problem and how to solve it. Thank you so much!

I answered this question on SO.