我正在尝试编译一些 CUDA,并且希望显示编译器警告。相当于:
g++ fish.cpp -Wall -Wextra
除非 NVCC 不明白这些,你必须通过它们:
nvcc fish.cu --compiler-options -Wall --compiler-options -Wextra
nvcc fish.cu --compiler-options "-Wall -Wextra"
(我喜欢后一种形式,但最终,这并不重要。)
鉴于此 CMakeLists.txt (一个非常精简的示例):
cmake_minimum_required(VERSION 3.9)
project(test_project LANGUAGES CUDA CXX)
list(APPEND cxx_warning_flags "-Wall" "-Wextra") # ... maybe others
add_compile_options("$<$<COMPILE_LANGUAGE:CUDA>:--compiler-options ${cxx_warning_flags}>")
add_executable(test_cuda fish.cu)
但这扩展到:
nvcc "--compiler-options -Wall" -Wextra ...
这显然是错误的。 (省略生成器表达式周围的引号只会让我们陷入破碎的扩展地狱。)
...跳过蒙特卡洛编程的数千次迭代...
我已经到达了这颗宝石:
set( temp ${cxx_warning_flags} )
string (REPLACE ";" " " temp "${temp}")
set( temp2 "--compiler-options \"${temp}\"" )
message( "${temp2}" )
打印出令人鼓舞的外观
--compiler-options "-Wall -Wextra"
但是然后
add_compile_options("$<$<COMPILE_LANGUAGE:CUDA>:${temp2}>")
扩展为:
nvcc "--compiler-options \"-Wall -Wextra\"" ...
我不知所措;我在这里陷入了死胡同吗?或者我错过了一些关键的标点符号组合?
我正在回答我自己的问题,因为我找到了一些有效的解决方案,但我仍然有兴趣听听是否有更好的(阅读:更干净,更规范)的方法。
TL;博士:
foreach(flag IN LISTS cxx_warning_flags)
add_compile_options("$<$<COMPILE_LANGUAGE:CUDA>:--compiler-options=${flag}>")
endforeach()
逐一叙述:
我试过这个:
foreach(flag IN LISTS cxx_warning_flags)
add_compile_options("$<$<COMPILE_LANGUAGE:CUDA>:--compiler-options ${flag}>")
endforeach()
但这仍然给了
nvcc "--compiler-options -Wall" "--compiler-options -Wextra"
nvcc fatal : Unknown option '-compiler-options -Wall'
添加临时的:
foreach(flag IN LISTS cxx_warning_flags)
set( temp --compiler-options ${flag}) # no quotes
add_compile_options("$<$<COMPILE_LANGUAGE:CUDA>:${temp}>")
endforeach()
给出了新的结果:
nvcc --compiler-options -Wall -Wextra ...
nvcc fatal : Unknown option 'Wextra'
我假设这里发生的是CMake正在组合重复的
--compiler-options
标志,但我只是推测。
所以,我尝试使用等号消除空格:
foreach(flag IN LISTS cxx_warning_flags)
add_compile_options("$<$<COMPILE_LANGUAGE:CUDA>:--compiler-options=${flag}>")
endforeach()
万岁!我们有一个获胜者:
nvcc --compiler-options=-Wall --compiler-options=-Wextra ...
结语:
我们可以不用循环来做吗?
add_compile_options("$<$<COMPILE_LANGUAGE:CUDA>:--compiler-options=${cxx_warning_flags}>")
不起作用(
--compiler-options=-Wall -Wextra
),但是:
string (REPLACE ";" " " temp "${cxx_warning_flags}")
add_compile_options("$<$<COMPILE_LANGUAGE:CUDA>:--compiler-options=${temp}>")
确实有效(
"--compiler-options=-Wall -Wextra"
)。
我对最后一个选项有点惊讶,但我认为这是有道理的。总的来说,我认为循环选项的意图是最明确的。
编辑: 在使用 CMake 通过 NVCC 传递给 MSVC 的混淆标志中,我花了很多时间发现使用它可能会更好:
add_compile_options("$<$<COMPILE_LANGUAGE:CUDA>:-Xcompiler=${flag}>")
自从 CMake 出现对标志进行一些合理化以消除重复和歧义时,但没有意识到
--compiler-options
与它喜欢的 -Xcompiler
相同。
NVCC_PREPEND_FLAGS="<your nvcc flags here>" <CMake invocation>
(或将其直接集成到 CMake 中)可以解决问题吗?
我有点不确定我的解决方案是否适用于您的问题,它看起来太复杂,但我相信您面临着 g++ 和 nvcc 理解不同标志并希望直接将标志定位到 nvcc 的相同问题。