在CMake中指定CUDA编译器

时间:2016-09-12 06:04:55

标签: cmake clang llvm llvm-clang

我正在尝试使用clang-3.9基于以下documentation构建一个cuda项目。但我想用cmake来构建我的项目。我已经将CMAKE_CC_COMPILER和CMAKE_CXX_COMPILER分别设置为clang和clang ++。

但问题是,如果我使用

file(GLOB_RECURSE CUDA_SOURCES "./*.cu")
CUDA_ADD_LIBRARY(Benchmarks_CUDA ${CUDA_SOURCES})

在我的CMakeList.txt中,cmake默认使用nvcc编译器。但我想用clang来编译.cu文件。

相反,如果我使用

add_library (Benchmarks_CUDA ${CUDA_SOURCES})

然后我会收到错误

CMake Error: Cannot determine link language for target "Benchmarks_CUDA".
CMake Error: CMake can not determine linker language for target: Benchmarks_CUDA

有人可以告诉我如何使用cmake使用clang构建.cu文件。

1 个答案:

答案 0 :(得分:0)

恐怕我没有四年前能帮到你的答案。但是,通常情况下,使用新的 CMake 版本会显着改善情况。 CMake 3.18 was the first to officially support using Clang to compile CUDA. 我试过那个版本,但它不知道如何使用我的 clang++-12 安装。它可能是在 CMake 3.18 之后发布的。

没关系;在 CMake 3.19+ 上,使用 Clang 12 设置 CMAKE_CUDA_COMPILER“正常工作”。


首先,这里是 CMakeLists.txt:

cmake_minimum_required(VERSION 3.20)
project(clang-cuda-test LANGUAGES CUDA)

add_executable(
  vectorAdd
  # Sources
  vectorAdd.cu
  # Headers
  helper_cuda.h
  helper_string.h
)
target_include_directories(vectorAdd PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")

我已经从 CUDA 11 示例中复制了各种源文件。所以我将 Clang 12 设置为我的编译器(尽管请注意我的 CUDA 11 安装对于它来说太新了,这就是我收到警告的原因):

alex@alex-ubuntu:~/test$ cmake -G Ninja -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_CUDA_COMPILER=clang++-12
-- The CUDA compiler identification is Clang 12.0.1
-- Detecting CUDA compiler ABI info
-- Detecting CUDA compiler ABI info - done
-- Check for working CUDA compiler: /usr/bin/clang++-12 - skipped
-- Detecting CUDA compile features
-- Detecting CUDA compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /home/alex/test/build
alex@alex-ubuntu:~/test$ cmake --build build/ -- -v
[1/2] /usr/bin/clang++-12   -I../ -O3 -DNDEBUG --cuda-gpu-arch=sm_52 --cuda-path=/usr/local/cuda -MD -MT CMakeFiles/vectorAdd.dir/vectorAdd.cu.o -MF CMakeFiles/vectorAdd.dir/vectorAdd.cu.o.d -x cuda -c ../vectorAdd.cu -o CMakeFiles/vectorAdd.dir/vectorAdd.cu.o
clang: warning: Unknown CUDA version. cuda.h: CUDA_VERSION=11030. Assuming the latest supported version 10.1 [-Wunknown-cuda-version]
[2/2] : && /usr/bin/clang++-12  CMakeFiles/vectorAdd.dir/vectorAdd.cu.o -o vectorAdd  -lcudadevrt  -lcudart_static  -lrt  -lpthread  -ldl -L"/usr/local/cuda/lib64" && :
alex@alex-ubuntu:~/test$ ./build/vectorAdd 
[Vector addition of 50000 elements]
Copy input data from the host memory to the CUDA device
CUDA kernel launch with 196 blocks of 256 threads
Copy output data from the CUDA device to the host memory
Test PASSED
Done