Sign in to follow this  

Problem w/ static const member variable in DLL

This topic is 3465 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm sure there is a simple solution for this problem but I've had trouble finding something on the web. I'm getting linker errors when I try to use a static member variable from a class exported to a DLL. For example,
// foo.h
class MY_API Foo
{
public:
    void moofa() {}

public:
    static const int bar;
};

// foo.cpp
const int Foo::bar = 0;


All is good if I create an instance and call moofa(), but if I try to reference Foo::bar I get a linking error (unable to find symbol). What do I need to do to export this static member variable correctly? [edit] If anyone knows a good source of info relating to DLLs, I'd really like to know (NB: that excludes MSDN)

Share this post


Link to post
Share on other sites
Well with static constants that are of integral type, you can initialize them directly in the class declaration. Eg:

// foo.h
class MY_API Foo
{
public:
void moofa() {}

public:
static const int bar = 0;
};


Then you do not need to define it in any cpp file.

I don't know if that will fix your linking problem though, but since the definition has moved from the source to the header, it might.

Share this post


Link to post
Share on other sites
Thanks for the help, but I think I've found the problem. The problem was in the way I was declaring the API macro. I was using

// export.h
#ifdef _USRDLL
#define MY_API_EXPORT __declspec(dllexport)
#define MY_API_IMPORT __declspec(dllimport)
#ifdef MYDLL_EXPORTS
#define MY_API MY_API_EXPORT
#else
#define MY_API MY_API_IMPORT
#endif
#else
#define MY_API
#define MY_API_EXPORT
#define MY_API_IMPORT
#endif

// foo.h
class MY_API Foo
{
};


Because I want to be able to create either a dynamic or static library. I wasn't defining _USRDLL in the project that imported the DLL. When I do that, it works. Why this was only a problem for the static member variable, I don't know. The member functions seemed to work fine.

Share this post


Link to post
Share on other sites

This topic is 3465 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this