Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

windows

dll

//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?

like image 845
Nullptr Avatar asked Apr 21 '15 12:04

Nullptr


1 Answers

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.

like image 97
Axel Borja Avatar answered Oct 29 '22 20:10

Axel Borja