c++cgccpreprocessor

Is there a way to have the same #define statement in different files that are included into the same file


So, I have a file structure like this:

FileA includes FileB and FileC

FileB has:

#define image(i, j,    w) (image[ ((i)*(w)) + (j) ])

and FileC has:

#define image(i, j,    h) (image[ ((j)*(h)) + (i) ])

on compilation i get:

warning: "image" redefined

note: this is the location of the previous definition ...

Does this warning mean it changes the definition of the other file where it found it initially when compiling ?

Is there any way to avoid this warning while maintaining these two defines, and them applying their different definitions on their respective files?


Solution

  • Does this warning mean it changes the definition of the other file where it found it initially when compiling ?

    The program is ill-formed. The language doesn't specify what happens in this case. If the compiler accepts an ill-formed program, then you must read the documentation of the compiler to find out what they do in such case.

    Note that the program might not even compile with other compilers.

    Is there any way to avoid this warning while maintaining these two defines, and them applying their different definitions on their respective files?

    Technically, you could use hack like this without touching either header:

    #include "FileB"
    #undef image
    #include "FileC"
    

    But a good solution - if you can modify the headers - is to not use macros. Edit the headers to get rid of them. Use functions instead, and declare them in distinct namespaces so that their names don't conflict.


    Some rules of thumb:

    They are not functionally equivalent, one can be seen as a row-wise iteration and the other a column-wise

    This seems like a good argument for renaming the functions (or the macros, if you for some reason cannot replace them). Call one row_wise and the other column_wise or something along those lines. Use descriptive names!