views:

664

answers:

3

As the title suggests, is it correct or valid to import/export static data from within a C++ class?

I found out my problem - the author of the class I was looking at was trying to export writable static data which isn't supported on this platform.

Many thanks for the responses however.

+1  A: 

Is it correct inasmuch as it'll work and do what you expect it to? Assuming that you are talking about using _declspec(dllexport/dllimport) on a class or class member, yes, you can do that and it should give you the expected result - the static data would be accessible outside your dll and other C++ code could access it provided that that C++ access specification (public/protected/private) wouldn't block outside access in the first place.

Is it a good idea? Personally I don't think so as you would be exposing class internals not only within your library but to the outside world, which means that it will be pretty much impossible to change what is an implementation detail at the end of the day. Ask yourself if you are 100% certain if the interface of this class and large parts of its implementation will never, ever change...

Timo Geusch
+2  A: 

An exported C++ class means that the DLL clients have to use the same compiler as the DLL because of name mangling and other issues. This is actually a pretty big problem, I once had to write C wrappers to a bunch of C++ classes because the client programs had switched to MSVC9, while the DLL itself was using MSVC71. [There were some other complications with switching the DLL to MSVC90]. Since then I've been quite skeptical about this business of exporting classes, and prefer to write a C wrapper for everything.

Now, if you're willing to pay the price of exporting classes, I'd say that exporting static data doesn't make the problem any worse. Arguably, among the kinds of things you could export, it is safest to export static constants. Even so, I'd rather not do it, because like Timo says, you're now locked into this implementation.

One of the frameworks that I worked on required its clients to provide a set of error code constants. Over time, we found that using a simple bunch of constants was too brittle, and we switched to an OO design. We had a default implementation that would return the common error codes, but each of the error codes was accessed using a virtual function which could be overridden by individual clients - and they used it from some advanced device specific error handling. This solution proved far more scalable than the one based on exporting constants.

I'd suggest that you think long and hard about how you expect the component to evolve before you exporting static variables.

Pramod
A: 

dllexport (or import) on a class's (non-static) data member does nothing. Exported "things" are either functions or global data (though this is a questionable design choice). dllexport on a class is just a shortcut for saying "export all of these functions".

Adam Mitz