简体   繁体   English

#ifdef / #ifndef和#endif

[英]#ifdef / #ifndef and #endif

I have a piece of code that has to be run both on a CPU and CUDA-GPU and an other piece of code running on CPU alone. 我有一段代码必须同时在CPU和CUDA-GPU上运行,而另一段代码只能在CPU上运行。 #define ENABLE_CUDA is what i 'turn on' to enable the CUDA code in the entire application. #define ENABLE_CUDA是我“启用”以在整个应用程序中启用CUDA代码的功能。 Here is what my code looks like.... 这是我的代码的样子。

# define ENABEL_CUDA is the preprocessor directive to turn ON/OFF CUDA code.

CPU and GPU code --This piece of code has to be executed irrespective of whether CUDA is ON / OFF.

standalone CPU code alone -- This piece of code has to be executed only if CUDA is OFF.

My solution is : 我的解决方案是:

#ifdef ENABLE_CUDA

  CPU AND GPU code
# else
  CPU AND GPU code
  standalone CPU code 
# endif

But this involves code duplication (CPU AND GPU code) in both the ifdef and else blocks, I would like to avoid it. 但这涉及ifdef和else块中的代码重复(CPU和GPU代码),我想避免这种情况。

How can I accomplish it? 我该怎么做? What has to be done inorder to avoid duplication of code ? 为了避免重复代码必须做什么? Any pointers regarding this appreciated... 任何对此表示赞赏的指针...

#ifdef ENABLE_CUDA

  CPU AND GPU code
# else
  CPU AND GPU code
  standalone CPU code 
# endif

Is equivalent to: 等效于:

  CPU AND GPU code
# ifndef ENABLE_CUDA
  standalone CPU code 
# endif

In general, if code is common to both if and else you can move it out of both. 通常,如果代码对于ifelse都是通用的, if可以将它们移出两者。

Why not simply use: 为什么不简单使用:

CPU AND GPU code

#ifndef ENABLE_CUDA
  standalone CPU code 
# endif

Beside what the others have already said, 除了别人已经说过的话,

#ifndef ENABLE_CUDA
# define __device__
#endif

will take you a long way writing functions that run on the device if CUDA is present or on the host if not, without code duplication. 如果没有CUDA,将使您编写在设备上运行的功能(如果没有CUDA)或在主机上运行的功能(如果没有的话)很长。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM