Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the scope of a c++ macro redefinition?

Tags:

c++

visual-c++

I have a c++ implementation file (my.cpp) that indirectly includes a header file (b.h) that defines _MAX_DRIVE:

// b.h
#define _MAX_DRIVE  64

Then my.cpp includes stdlib.h which also defines _MAX_DRIVE

// stdlib.h
#define _MAX_DRIVE  3   /* max. length of drive component */

Obviously this produces a macro-redefinition warning:

stdlib.h(185) : warning C4005: '_MAX_DRIVE' : macro redefinition

My questions are:

  1. How much code is affected by this redefinition, is it just the compilation unit for my.cpp?
  2. Could the redefined value make its way in to other code if my.cpp is part of a static library?
  3. If I never even reference _MAX_DRIVE in my.cpp, is is safe to tell the compiler to ignore this macro redefinition warning?
like image 607
Matthew Avatar asked Oct 15 '25 03:10

Matthew


2 Answers

  1. It's until the end of the current compilation unit, or until the next #undef.
  2. No; macro names are only seen by the preprocessor, which finishes running before compilation even begins.
  3. It doesn't sound like a very sensible idea. It would be a better idea to avoid having two macros with the same name (especially one that begins with a single underscore followed by a capital letter, as they're reserved for the implementation).
like image 108
Oliver Charlesworth Avatar answered Oct 18 '25 00:10

Oliver Charlesworth


How much code is affected by this redefinition, is it just the compilation unit for my.cpp?

It affects ALL files that includes b.h and stdlib.h, if it's never #undef-ed

Could the redefined value make its way in to other code if my.cpp is part of a static library?

No, preprocessor symbols lives only at compilation time. Compiled modules have nothing to do with it.

If I never even reference _MAX_DRIVE in my.cpp, is is safe to tell the compiler to ignore this macro redefinition warning?

Yes, until someday you or any of your code's users use it and forget or don't know about this danger.

like image 37
LeleDumbo Avatar answered Oct 18 '25 00:10

LeleDumbo