C ++ How to export a static member of a class from dll?

// API mathAPI.h, both in Dll.cpp and in Test.cpp

#ifdef __APIBUILD #define __API __declspec(dllexport) //#error __APIBUILD cannot be defined. #else #define __API __declspec(dllimport) #endif class math { public: static __API double Pi; static __API double Sum(double x, double y); }; 

//Dll.cpp __APIBUILD defined

 #include "mathAPI.h" double math::Pi = 3.14; double math::Sum(double x, double y) { return x + y; } 

//Test.cpp __APIBUILD not defined

 #include <iostream> #pragma comment(lib, "dll.lib") #include "mathAPI.h" int main() { std::cout << math::Pi; //linker error std::cout << math::Sum(5.5, 5.5); //works fine return 0; } 

Error 1 error LNK2001: unresolved external character "public: static double Math :: Pi" (? Pi @Math @@ 2NA)

How can I make this work?

+5
source share
2 answers

The best solution to get the Pi value is to create a static method to initialize and return it, as shown below in your DLL.cpp:

 #include "mathAPI.h" // math::getPi() is declared static in header file double math::getPi() { static double const Pi = 3.14; return Pi; } // math::Sum() is declared static in header file double math::Sum(double x, double y) { return x + y; } 

This will prevent you from uninitialized Pi value and do what you want.

Note that the best practice of initializing all static values ​​/ members is to initialize them when calling the function / method.

+2
source

Instead of exporting items, export the entire class one by one. In addition, I don’t completely know how this code can work - you did not specify a definition for sum() (the missing class scope operator) and what the linker should refer to (instead of math::Sum() you defined a new global sum() ).

mathAPI.h

 #ifdef __APIBUILD #define __API __declspec(dllexport) #else #define __API __declspec(dllimport) #endif class __API math //Add __API to export whole class { public: static double Pi; static double Sum(double x, double y); }; 

Dll.cpp

 #include "mathAPI.h" double math::Pi = 3.14; double math::Sum(double x, double y) //You missed 'math::' here before { return x + y; } 

What is it.


EDIT

However, you should still receive an error message. This is because you made a typo that I did not notice (and you did not publish the real code!). In your Dll.cpp , you wrote:

 double math::Pi = 3.14; 

Although you posted something else, I'm sure your class has the name Math , not Math , because the linker is trying to find:

 ?Pi@Math @@2NA 

So he looks in the Math class. This is the most likely assumption. Although, I am sure that you did not publish the real code, but a handwritten fragment.

0
source

All Articles