IT Share you

정적 변수 링크 오류

shareyou 2020. 11. 24. 20:38
반응형

정적 변수 링크 오류


Mac에서 C ++ 코드를 작성하고 있습니다. 컴파일 할 때이 오류가 발생하는 이유는 무엇입니까? :

아키텍처 i386에 대한 정의되지 않은 기호 : "Log :: theString", 참조 : Log :: method (std :: string) in libTest.a (Log.o) ld : symbol (s) not found for architecture i386 clang : error : 링커 명령이 종료 코드 1로 실패했습니다 (호출을 보려면 -v 사용).

내 코드가 잘못되었거나 Xcode에 플래그를 추가해야하는지 확실하지 않습니다. 내 현재 XCode 구성은 '정적 라이브러리'프로젝트의 기본 구성입니다.

내 코드 :

Log.h ------------

#include <iostream>
#include <string>

using namespace std;

class Log{
public:
    static void method(string arg);
private:
    static string theString ;
};

Log.cpp ----

#include "Log.h"
#include <ostream>

void Log::method(string arg){
    theString = "hola";
    cout   << theString << endl; 
}

다음과 같이 테스트 코드에서 'method'를 호출합니다. 'Log :: method ( "asd") :'

당신의 도움을 주셔서 감사합니다.


cpp파일 에서 정적을 정의해야 합니다.

Log.cpp

#include "Log.h"
#include <ostream>

string Log::theString;  // <---- define static here

void Log::method(string arg){
    theString = "hola";
    cout   << theString << endl; 
}

using namespace std;헤더 에서도 제거해야합니다 . 할 수있을 때 습관을들이십시오. 이것은 std헤더를 포함 할 때마다 전역 네임 스페이스를 오염시킵니다 .


을 선언 static string theString;했지만 정의하지 않았습니다.

포함

string Log::theString;

당신의 cpp파일에

참고 URL : https://stackoverflow.com/questions/9282354/static-variable-link-error

반응형