开发者

Exposing Static Constant with Boost

开发者 https://www.devze.com 2023-03-24 09:51 出处:网络
I am using Boost 1.44.0 to cross-compile C++ code for Python. I\'m trying to expose a static constant d开发者_开发知识库efined in ExposureSinusoid.h like this:

I am using Boost 1.44.0 to cross-compile C++ code for Python. I'm trying to expose a static constant d开发者_开发知识库efined in ExposureSinusoid.h like this:

static const UINT _min_exp = 20;

And in the file extending.cpp, I am trying to expose them like this, according to documentation from the Boost team:

.def_readonly("_min_exp", &ExposureSinusoid::_min_exp)

The library compiles fine but when the program runs I get the following error:

ImportError: ../linux/appfs/master/usr/lib/python2.6/pa/vision/_vision.so: undefined symbol: _ZN16ExposureSinusoid8_min_expE

To rule out the possibility the Boost wasn't finding the constant, I tried changing its name in extending.cpp and the library failed to compile. So it seems like the constant is being found during compilation but it isn't being properly exposed.


In addition to being declared, static data members must also be defined.

// ExposureSinusoid.h
class ExposureSinusoid
{
    // ...
public:
    static const UINT _min_exp = 20;   // declaration
    // ...
};

// ExposureSinusoid.cpp
const UINT ExposureSinusoid::_min_exp; // definition

The only scenario where the definition of a static data member may be omitted is when the data member in question is a const fundamental integral type, and it is initialized with a constant expression, and it is never ODR-used (see the C++03 standard, §9.4.2/4); however, taking the address of a variable qualifies as ODR-usage, so in your case a definition must be supplied.


Static linkage means that the symbol is not visible outside the TU! Change static to extern (because global constants are implicitly static):

extern const UINT _min_exp = 20;

Correction: I didn't see that _min_exp was a member variable, apologies. In that case the answer is, as ildjarn already said, to add the definition of the variable outside the class definition. To be sure, both the declaration and the initialization go inside, but the definition goes outside:

struct Foo {
  static const int a = 1; // initialization can go inside the class definition
};
const int Foo::a;         // definition (this is what the linker sees)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号