Uma macro CUDA_CHECK reutilizável
Envolva cada chamada para garantir segurança.
Uma macro CUDA_CHECK reutilizável é uma aula grátis de CUDA Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de CUDA Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de CUDA Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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. 🎉
Perguntas Frequentes
A aula “Uma macro CUDA_CHECK reutilizável” é grátis?
Sim — o texto completo de “Uma macro CUDA_CHECK reutilizável” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de CUDA Academy, atualize para CoddyKit PRO. O curso de CUDA Academy inclui 4 aulas no total.
O que vou aprender em “Uma macro CUDA_CHECK reutilizável”?
Envolva cada chamada para garantir segurança. Você pratica CUDA Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar CUDA Academy?
Nenhuma experiência prévia é necessária. CUDA Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “Uma macro CUDA_CHECK reutilizável”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de CUDA Academy?
Sim. Cada aula de CUDA Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Códigos de retorno versus erros assíncronos
- cudaGetLastError após a execução
- Uma macro CUDA_CHECK reutilizável
- Decodifique cudaGetErrorString