0Pricing
CUDA Academy · Lección

Una macro CUDA_CHECK reutilizable

Envuelva cada llamada para mayor seguridad.

Una macro CUDA_CHECK reutilizable es una lección gratuita de CUDA Academy en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de CUDA Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de CUDA Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Checking Every Call Is Tedious

Writing an if-statement after every CUDA call clutters your code fast. A reusable CUDA_CHECK macro fixes that with one clean line. 🧹

The Goal of the Macro

You want to wrap any call, grab its return code, and bail out loudly if it failed. One macro can do this everywhere.

CUDA_CHECK(cudaMalloc(&d, n));

Capturing the Result

Inside, the macro stores the call result in a local cudaError_t so it can be inspected once without calling twice.

cudaError_t e = (call);

Comparing to Success

It then tests the code against cudaSuccess. If they match, nothing happens and your program flows on as normal.

if (e != cudaSuccess) { /* report */ }

Printing Where It Failed

On failure it prints a readable message using __FILE__ and __LINE__, so you jump straight to the offending line.

printf("CUDA error %s at %s:%d\n", msg, __FILE__, __LINE__);

The do-while(0) Trick

The body is wrapped in a do-while(0). This makes the macro a single statement that works safely even inside an unbraced if.

#define CUDA_CHECK(c) do { /* ... */ } while(0)

A Full Macro Sketch

Put it together and you get a compact, reusable safety net you can paste into any CUDA project header.

#define CUDA_CHECK(c) do { cudaError_t e=(c); if(e) exit(1); } while(0)

Wrapping API Calls

Use it on any call that returns a code: cudaMalloc, cudaMemcpy, cudaFree. One wrapper guards them all uniformly.

CUDA_CHECK(cudaMemcpy(d, h, n, cudaMemcpyHostToDevice));

Also Guard the Launch

Kernels return nothing, so wrap cudaGetLastError and a sync after the launch instead of wrapping the launch line itself.

kernel<<<g, b>>>();
CUDA_CHECK(cudaGetLastError());

Keep It in a Header

Drop the macro in a shared header so every file uses the same check. Consistency here saves hours of confusing debugging.

Fail Fast, Fail Clearly

The big win is failing fast: the instant a call breaks, you get a precise file, line, and message instead of silent garbage.

Quick Check

Test your grasp of the CUDA_CHECK macro.

Recap: One Macro to Guard Them All

A CUDA_CHECK macro captures the code, compares to success, and prints file and line on failure. Define it once, use it everywhere. 🎉

Preguntas frecuentes

¿La lección «Una macro CUDA_CHECK reutilizable» es gratis?

Sí — el texto completo de «Una macro CUDA_CHECK reutilizable» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de CUDA Academy, actualiza a CoddyKit PRO. El curso de CUDA Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Una macro CUDA_CHECK reutilizable»?

Envuelva cada llamada para mayor seguridad. Practicas CUDA Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar CUDA Academy?

No se requiere experiencia previa. CUDA Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.

¿Cuánto tiempo toma la lección «Una macro CUDA_CHECK reutilizable»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de CUDA Academy?

Sí. Cada lección de CUDA Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Códigos de retorno frente a errores asíncronos
  2. cudaGetLastError después del lanzamiento
  3. Una macro CUDA_CHECK reutilizable
  4. Descifrar cudaGetErrorString
← Volver a CUDA Academy