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

这一生的挚爱 提交于 2021-01-27 18:54:46

问题


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!


回答1:


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.



回答2:


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.



来源:https://stackoverflow.com/questions/6602543/c-what-might-cause-unresolved-external-errors-in-he-link-process-when-using-st

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!