checking #ifdef from a different Compilation Unit

Started by
9 comments, last by nlbs 15 years, 8 months ago
I've a macro say MY_MACRO which is defined in main.cpp is it possible to access this macro using #ifdef and friends from a different Compilatin unit that is included through Its header File. I dont see it as possible. Is it Possible with some tricks ??
Advertisement
Translation units are compiled in isolation. If you put the macro in a header file you can access it by including that header file from both source files.
Hmm so If I want to put the MY_SESS Macro in main.cpp it is not possible to access it from other units Right ??
Quote:Original post by nlbs
Hmm so If I want to put the MY_SESS Macro in main.cpp it is not possible to access it from other units Right ??


Correct.
[TheUnbeliever]
You can usually pass preprocessor macros to the compiler directly. Many libraries use this, for example they may have a USE_THREADING macro, or USE_FROB_LIB to use the frob library for any frobnication that is necessary.
macros.hpp
#define MY_MACRO


....

foo.hpp
bar.hpp
baz.hpp
#include "macros.hpp"#ifdef MY_MACRO...


Or am I missing something?
But What I've tried is
I defined a macro MY_MACRO in main.cpp
and tried to access it from libxyz.cpp
which failed cause that macro is not included by libxyz.cpp

Now as the macros will be used for configuration directive I've another plan which is more structured.

say I've made a Class named Config{.....} and There I'll put static member variable and their getter and setter there will be its forwartd declearation on both main.cpp and the libxyz.cpp and I can do Config::x = 2 before main() in the main.cpp and access Config::x from the libxyz.cpp

so how is the Plan ??
is it good or Impactrical or non standered or faulty ??
Can you give a more concrete example of what you are doing?

The preprocessor should be reserved for conditional compilation where possible. However, your Config solution sounds a little over engineered.
session.h
class Session{  private:    string sessPath;  public:    Session();    ........

session.cpp
//Calling SessionConfig::getSessPath() which is the static method of static Config ClassSession::Session():sessPath(SessionConfig::getSessPath()){  //Its possible to set a default value by SessionConfig::getSessPath().  //and gain if it gets called for second time the.  //previous value get overridden with the new one.}.........

main.cpp
....class SessionConfig;int main(int argc, char *argv[]){  SessionConfig::setSessPath("/tmp/cgi++/session");  Session session;  ......}

all forward declearation is done acordingly.

SessionConfig is the Config Class that holds static private variables along with there static getter and setters.

I've tested this way and it not only works rathar it ROCKS
So... what happened to macros?

This topic is closed to new replies.

Advertisement