开发者

C++ What might cause unresolved external errors in he link process when using static members of a class?

开发者 https://www.devze.com 2023-03-18 22:28 出处:网络
I made a program that has a class with static-only members in it in its own dedicated cpp/h file combo. The probably is that when I try to use these static members in my code, I\'m getting \"unresolve

I made a program that has a class with static-only members in it in its own dedicated cpp/h file combo. The probably is that when I try to use these static members in my code, I'm getting "unresolved external" errors at the linker stage. I am remembering to include the h file in my cpp file that is getting the errors. I don't understand. Is this the wrong design approach to take?

Basically i want some global objects that are part of a third party API to be available to my whole program, so I organized everything into one class and made everything a static member. I also made an empty private constructor to keep the class from being instantiated. Is开发者_开发百科 this a sensible approach? The static members are all pointers and I tried to start out by allocating new objects and attaching each to the static poonters. Is here a problem with this approach?

Thanks!


Are you remembering to actually define the variable somewhere, instead of just declaring it in the header?

Foo.hpp:

#ifndef FOO_HPP
#define FOO_HPP

class Foo {
public:
  static int bar;
};

#endif

Foo.cpp:

#include "Foo.hpp"

int Foo::bar; // <-- This being the critical line.


If you are accessing global objects in a third-party library, you need to make sure you are linking with that library. Just compiling against the headers for the library won't do it.

0

精彩评论

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