C++如何从dll导出静态类成员?

Nul*_*ptr 8 c++ windows dll

// API mathAPI.h,在Dll.cpp和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);
};
Run Code Online (Sandbox Code Playgroud)

//定义了Dll.cpp __APIBUILD

#include "mathAPI.h"

double math::Pi = 3.14;

double math::Sum(double x, double y)
{
  return x + y;
}
Run Code Online (Sandbox Code Playgroud)

// Test.cpp __APIBUILD未定义

#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;
}
Run Code Online (Sandbox Code Playgroud)

错误1错误LNK2001:未解析的外部符号"public:static double Math :: Pi"(?Pi @ Math @@ 2NA)

我如何让这个工作?

Axe*_*rja 5

获取 Pi 值的更好解决方案是创建一个静态方法来初始化并返回它,就像 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;
}
Run Code Online (Sandbox Code Playgroud)

这将防止您使用未初始化的值 Pi,并且会做您想做的事。

请注意,初始化所有静态值/成员的最佳实践是在函数/方法调用中初始化它们。