views:

40

answers:

4

The following macro is defined in our code:

#define  MSGMacro(obj, arg)  MyPaymentClass obj(arg)

Where MSGMacro is used to creates the object of type MyPaymentClass using code like

MSGMacro(Card, 1);
MSGMacro(Cash, 2);
----
---- //removed unwanted things to keep question cleaner. 

All the above code is in one cpp file, Now the problem is how we can expose these two objects of MyPaymentClass to other units in my project? i.e. I want to use Card and Cash in other CPP files. Please suggest how I can give the declaration for the same in some header file?

+1  A: 

I can't figure out why you would use a macro in this case, it's just as easy to declare the object. As far as exposing these instances you could make them global static objects but that is generally frowned upon. You should figure out how these objects relate to the rest of your application and find an appropriate place to expose them to the rest of your code.

bshields
I also wonder about the value of these macros, but maybe they've been simplified for posting in a question here?
Michael Burr
U are right Michael the things were cleaned and re-written Just to post question clearly.
Learner
+1  A: 

You could create accessor functions:

const MyPaymentClass &getCard()
{
    return card;
}

You would also need to add a prototype for that function to the header file:

const MyPaymentClass &getCard();
R Samuel Klatchko
A: 

Are these global objects? Then a simple extern MyPaymentClass Card; and extern MyPaymentClass Cash; should do the trick (discussion about the appropriateness of global vars elided).

Of course you can also pass references or pointers to those objects to other functions, regardless of whether or not they're global variables (but you would still have to take into consideration the lifetime of those objects if they aren't static/global).

Michael Burr
+1  A: 

Create another macro to declare these variables:

/* example.h */
#define MSGMacroDeclare(obj) extern MyPaymentClass obj;
MSGMacroDeclare(Card);
MSGMacroDeclare(Cash);
...

/* example.cpp */
#define MSGMacroDefine(obj, arg) extern MyPaymentClass obj(arg);
MSGMacroDefine(Card, 1);
MSGMacroDefine(Cash, 2);
...

Eventually if you want the same file to booth declare and define them, you can use sth like this:

/* example.h */
#ifndef MSGMacro
     #define MSGMacro(obj, arg) extern MyPaymentClass obj
#endif
MSGMacro(Card, 1);
MSGMacro(Cash, 2);
...

/* example.cpp */
#define MSGMacro(obj, arg) extern MyPaymentClass obj(arg)
#include "example.h"

but this makes sense only when there are many, many, many of these (many globals? hmmm...) and the list is being changed frequently, generally this is unusual

adf88