简体   繁体   中英

Multi-line macro results in "Expected a Declaration" error

I am trying to use CUDA C for GPU computing, in particular matrix inversion problem. Meanwhile at the beginning of my code I have defined function. But, that seems to give me an error of "expected declation" at the line where I initiate "do".

I am new to C++ so haven't tried much.

#include<cublas_v2.h>
#include<stdio.h>
#include<math.h>
#include<stdlib.h>

#define cudacall(call)
    do
    {
        cudaError_t err = (call);
        if (cudaSuccess != err)
        {
            fprintf(stderr, "CUDA Error:\nFile = %s\nLine = %d\nReason = %s\n", __FILE__, __LINE__, cudaGetErrorString(err));
            cudaDeviceReset();
            exit(EXIT_FAILURE)
        }
    }
    while (0);

"Expected Declaration"

Multi-line macros need to have a \\ to indicate that they continue on the next line. I lined all of them up at the end; scroll to see them.

#define cudacall(call)                                                         \
  do {                                                                         \
    cudaError_t err = (call);                                                  \
    if (cudaSuccess != err) {                                                  \
      fprintf(stderr, "CUDA Error:\nFile = %s\nLine = %d\nReason = %s\n",      \
              __FILE__, __LINE__, cudaGetErrorString(err));                    \
      cudaDeviceReset();                                                       \
      exit(EXIT_FAILURE)                                                       \
    }                                                                          \
  } while (0);

In general, please avoid macros if you can. Use lambdas and higher-order functions instead:

template<class F> 
void cudacall(F&& func) {                                                                    
    cudaError_t err = func();                                                  
    if (cudaSuccess != err) {                                                  
        fprintf(stderr, "CUDA Error:\nFile = %s\nLine = %d\nReason = %s\n",      
              __FILE__, __LINE__, cudaGetErrorString(err));                    
        cudaDeviceReset();                                                       
        exit(EXIT_FAILURE);                                                     
    }                                                                          
}

We can use it like this:

void dostuff() {
    bool wasICalled = false;
    cudacall([&]() {
        // Code goes here

        // We can access and modify local variables inside a lambda
        wasICalled = true; 

        // Return the error
        return cudaError_t{}; 
    }); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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