//API mathAPI.h, both in Dll.cpp and 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 is 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 symbol "public: static double Math::Pi" (?Pi@Math@@2NA)
How do i get this to work?
The better solution to get your Pi value is to create a static method to init and return it, like the following 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 of uninitialised value Pi, and will do what you want.
Please note that the best practice to initialize all static values/members is to initialize them in a function/method call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With