简体   繁体   中英

Exporting global const variable from a DLL

The following is a simplified version of the code I am using with the Qt framework:

foo.h:

// Defines DLL import or export as required
#if defined(REGEXUTIL_LIBRARY)
  #define LIBRARY_EXPORT Q_DECL_EXPORT
#else
  #define LIBRARY_EXPORT Q_DECL_IMPORT
#endif

LIBRARY_EXPORT extern const QString testString;

foo.cpp:

#include "foo.h"
LIBRARY_EXPORT const QString testString = "Test string";

test.cpp, in module which imports this DLL:

const QString s = testString;

I know both the DLL and the test compile and link correctly since the above works with a non-const QString. However, when I make the QString const I get an unresolved external symbol error upon compiling the test, which I am assuming is to do with the fact that the const variable is not initialised in the header file. If I do initialise it there, I get errors about the DLL import prefix not being allowed when I attempt to compile the test.

What is the correct way to fix this error? I want to be able to access the const QString variables from modules which import this DLL.

If solution of const string being defined in header is acceptable to you, there is no need to import the symbol at all:

//foo.h
static const QString testString = "Test string";

should be enough - testString can be accessed both in modules importing the dll and inside the dll itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM