Programming

정적 클래스 멤버에서 해석되지 않은 외부 기호

procodes 2020. 7. 11. 12:05
반응형

정적 클래스 멤버에서 해석되지 않은 외부 기호


간단히 말해서 :

대부분 정적 공용 멤버로 구성된 클래스가 있으므로 다른 클래스 / 함수에서 호출해야하는 유사한 함수를 함께 그룹화 할 수 있습니다.

어쨌든, 클래스 공용 범위에서 두 개의 정적 부호없는 char 변수를 정의했습니다. 같은 클래스의 생성자에서 이러한 값을 수정하려고 할 때 컴파일 할 때 "해결되지 않은 외부 기호"오류가 발생합니다.

class test 
{
public:
    static unsigned char X;
    static unsigned char Y;

    ...

    test();
};

test::test() 
{
    X = 1;
    Y = 2;
}

저는 C ++을 처음 사용하므로 쉽게 사용할 수 있습니다. 왜 이렇게 할 수 없습니까?


X와 Y의 선언과 일치하도록 정의를 추가하는 것을 잊었습니다

unsigned char test::X;
unsigned char test::Y;

어딘가에. 정적 멤버를 초기화하고 싶을 수도 있습니다.

unsigned char test::X = 4;

그리고 다시, 선언이 아닌 정의 (보통 CXX 파일에서)에서 수행합니다 (종종 .H 파일에 있음)


클래스 선언의 정적 데이터 멤버 선언은 정의가 아닙니다. 그것들을 정의하려면 .CPP파일에서 중복 기호를 피하기 위해이 작업을 수행해야합니다 .

선언하고 정의 할 수있는 유일한 데이터는 정수 정적 상수입니다. (의 값은 enums상수 값으로도 사용될 수 있습니다)

코드를 다음과 같이 다시 작성할 수 있습니다.

class test {
public:
  const static unsigned char X = 1;
  const static unsigned char Y = 2;
  ...
  test();
};

test::test() {
}

당신은 당신이 정적 변수를 수정할 수있는 능력을 가지고 싶다면 당신이 사이에 당신에게 코드를 분리 할 수 있습니다 (즉 CONST로 선언하는 것은 적절 인 경우) .H.CPP다음과 같은 방법으로 :

.H :

class test {
public:

  static unsigned char X;
  static unsigned char Y;

  ...

  test();
};

.CPP :

unsigned char test::X = 1;
unsigned char test::Y = 2;

test::test()
{
  // constructor is empty.
  // We don't initialize static data member here, 
  // because static data initialization will happen on every constructor call.
}

이것은 일반적으로 "정적 const 멤버를 가진 해결되지 않은 외부 요소"를 검색 할 때 나에게 보이는 첫 번째 SO 스레드이므로, 해결되지 않은 외부 장치의 한 가지 문제를 해결하기위한 또 다른 힌트를 남길 것입니다.

For me, the thing that I forgot was to mark my class definition __declspec(dllexport), and when called from another class (outside that class's dll's boundaries), I of course got the my unresolved external error.
Still, easy to forget when you're changing an internal helper class to a one accessible from elsewhere, so if you're working in a dynamically linked project, you might as well check that, too.


in my case, I declared one static variable in .h file, like

//myClass.h
class myClass
{
static int m_nMyVar;
static void myFunc();
}

and in myClass.cpp, I tried to use this m_nMyVar. It got LINK error like:

error LNK2001: unresolved external symbol "public: static class... The link error related cpp file looks like:

//myClass.cpp
void myClass::myFunc()
{
myClass::m_nMyVar = 123; //I tried to use this m_nMyVar here and got link error
}

So I add below code on the top of myClass.cpp

//myClass.cpp
int myClass::m_nMyVar; //it seems redefine m_nMyVar, but it works well
void myClass::myFunc()
{
myClass::m_nMyVar = 123; //I tried to use this m_nMyVar here and got link error
}

then LNK2001 is gone.

참고URL : https://stackoverflow.com/questions/195207/unresolved-external-symbol-on-static-class-members

반응형