Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scoping C++ macros?

I am working on a large C++ project. I have a bunch of macros that are used in a subset of the project, but I don't want to export them everywhere, to avoid contaminating unrelated code.

Right now, many of my files look like

#include <MyMacros.h> // defines MACRO_1, MACRO_2, ... MACRO_N

// bla
// bla

#undef MACRO_1
#undef MACRO_2
// ...
#undef MACRO_N

Of course, this is going to break the day I introduce MACRO_N+1.

Is there a better way to do somehow undefine all these macros at once?

like image 926
Yoric Avatar asked Aug 03 '26 18:08

Yoric


1 Answers

You can create a separate include file that undefines the macros in question and include that in your source files.

For example, in undefMacros.h:

#undef MACRO_1
#undef MACRO_2
// ...
#undef MACRO_N

Then in your source files:

#include <MyMacros.h> // defines MACRO_1, MACRO_2, ... MACRO_N

// bla
// bla

#include <undefMacros.h>

Then you only need to maintain the #undef statements in one place, in addition to where the macros are originally defined.

like image 177
dbush Avatar answered Aug 06 '26 08:08

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!