c++ - Safer conditional compilation? -
in msvc c++ program have part of code want enable or disable depending on preprocessor definition
// 1.h #ifdef myoption //... #endif
but find quite dangerous when used in .h file included in more 1 compilation unit, can inconsistent headers (i don't want define myoption globally require complete recompilation each time change it):
// 1.cpp #define myoption #include "1.h" // 2.cpp #include "1.h"
of course, more complicated simplified example due chained header inclusion.
is there way avoid such inconsistency, e.g. have compile-time error without effort?
i thought of doing #define myoption 0
or 1
, have write like
#if myoption == 1 //... #elif !defined(myoption) #error ... #endif
which looks complicated... maybe there better option?
how this: have 1.h define dummy section in obj different options. way, if myoption ever used inconsistently, linker issue warning.
1.h:
#ifdef myoption #pragma section("myoption_guard",write) #else #pragma section("myoption_guard",read) #endif namespace { __declspec(allocate("myoption_guard")) int myoption_guard; }
compiling myoption defined in a.cpp not in b.cpp yields linker warning (using vc 2008):
b.obj : warning lnk4078: multiple 'myoption_guard' sections found different attributes (40300040)
a consistent definition yields no linker warnings @ all.
Comments
Post a Comment