Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to #define macro only to specific files?

Tags:

c++

I have a special macro defined in macro.h, but I want it to be valid only in part of my source files (h/cpp), how can I do that?

I am afraid that some "bad" user included the macro.h before the source files that must not be familiar with the macro.

how can I prevent it?

like image 476
bochaltura Avatar asked Dec 09 '12 15:12

bochaltura


1 Answers

It is possible to have macros that are defined only in a files scope by using #undef. E.g. :

#define MACRO 1

int a = MACRO;

#undef MACRO

int b = MACRO; // ERROR

However, this does not work across files unless you rely on the order of includes, which would be bad.

If you want to use macros defined in a macro.h in sources, you could have a second unmacro.h and include that at the end of the source:

 // foo.cpp
 // other includes
 #include "macro.h"
 // no other includes!

 // contents of the source

 #include "unmacro.h"

However, I would not recommended it because it is error-prone. Better reconsider if you need to use macros at all. In modern C++ their valid uses are extremely rare.

like image 124
463035818_is_not_a_number Avatar answered Oct 11 '22 15:10

463035818_is_not_a_number