Home > database >  how does macros defined avoid conflicts across source code headers and libraries?
how does macros defined avoid conflicts across source code headers and libraries?

Time:11-24

if I defined a ADD(x,y) macro in my cpp or header file. There is a dll I linked to that have defined their own ADD(x,y) macro. Would this cause a conflict?

What are cases where macros are global and cases where it is region specific?

CodePudding user response:

Yes, this would conflict, if both #defines are present, after applying #includes. If you aren't #includeing a header for this dll, then nothing involved in it's compilation can affect your code. It might have been compiled from a different language.

Macros are not functions, they do not obey namespacing, do not #define ADD(x,y) x y, instead, if you must, define a template

namespace jojo
{
    template <typename T> constexpr T add(T x, T y) { return x   y; }
}

Do note that since C 14, you can have a very similar function object

namespace jojo
{
    std::plus<> add;
}

As an aside, I would question the quality of a library that #defines ADD(x, y) as anything, and look for alternatives.

CodePudding user response:

C and C macros are specific to preprocessor, which substitutes them with their final values before your program is compiled. So, at link time, no direct reference to any macro will remain.

However, this doesn't prevent macros themselves to generate something that could interfere either with itself or anything else, triggering an error and giving the feeling it comes from these macros.

CodePudding user response:

Macros are removed from the code by the preprocessor, so when the code is compiled, there are no macros in it, so there will be no conflicts.

  •  Tags:  
  • c
  • Related