Search code examples
cc-preprocessor

How to avoid conflict between the definition of a function and macro with the same name?


I've defined a function and a macro like this to set the values inside of a matrix:

void init_matrix(Matrix *mat, double ea[],  size_t size)
{
    for (int i = 0; i < mat->row; i++)
        for (int j = 0; j < mat->col; j++) {
            if (!(i*mat->col+j<size))
                return;
            mat->entries[i][j] = ea[i*mat->col + j];    
        }
}

#define init_matrix(mat, ...) init_matrix(mat, (double []) {__VA_ARGS__}, sizeof((double []) {__VA_ARGS__})/sizeof(double))

It works fine now, but I was considering moving the function declarations and macros into a header file and then including that header file into this program. But when I do that, it'll probably make expand the definition of the function into something like:

void init_matrix(Matrix *mat, (double []) {double ea[], size_t size}, sizeof((double []) {double ea[], size_t size})/sizeof(double))

Which would mess everything up, right? How can I avoid that? Maybe putting this function at the end of the file and using an #undef init_matrix before it? Or is there a way to undefine a macro just in a section of the code and keep it working like it did before before and after that part?


Solution

  • You can use parentheses around the function name (and around the name in the prototype if you are using a header) to stop the expansion:

    void (init_matrix)(Matrix *, double[], size_t);
    void (init_matrix)(Matrix *mat, double ea[], size_t size)
    {
        ...
    }
    

    Take a look to What do the parentheses around a function name mean? for more info.