2010-05-06 3 views
0

함수 외부에서 정적 변수를 선언하고 함수 내부에서 정적 변수를 선언하는 것과 차이가 있습니까?정적 변수와 extern in plain C

또한 변수를 정적으로 선언하고 extern 변수를 선언하는 것의 차이점은 무엇입니까?

+1

가능한 복제 http://stackoverflow.com/questions/572547/what-does-static-mean-in-a-c-program. 참조 : http://stackoverflow.com/questions/534735/internal-static-variables-in-c-would-you-use-them#535012, http://stackoverflow.com/questions/1433204/what-are -extern-variables-in-c, http://stackoverflow.com/questions/1856599/when-to-use-static-keyword-before-global-variables#1856642, http://stackoverflow.com/questions/1358400/what-is-external-linkage-and-internal-linkage-in-c – outis

답변

4

차이점은 함수 내부의 정적 변수는 함수 내부에서만 볼 수 있지만 외부의 정적 변수는 선언 지점에서부터 변환 단위의 끝까지의 모든 함수에서 볼 수 있습니다.

그렇지 않으면 동일하게 동작합니다.

static 키워드없이 함수 외부에서 변수를 선언하면 해당 변수가 정의 된 파일 (번역 단위) 외부에서 볼 수 있음을 의미합니다 (번역 단위의 정의 지점에서 끝까지) . 변수를 extern으로 선언하면 동일한 번역 단위에 다른 정의가있을 수 있지만 다른 번역 단위에는 가능성이 높다는 의미입니다. 함수 내에서 extern 변수를 선언 할 수는 있지만 함수 밖에서 만 정의 할 수 있습니다.

0

첫 번째 예 :

class SoTest 
{ 
public: 
    SoTest(const char *name) 
    { 
     printf("C'tor called of %s\t(%#x) object\n",name,this); 
    } 
    static SoTest ClassStaticObj; 
}; 

static SoTest CStaticObj("CStaticObj"); 
SoTest SoTest::ClassStaticObj("ClassStaticObj"); 

void function() 
{ 
    for (int i = 0; i < 2;i++) 
    { 
     static SoTest FunctionStaticObj("FunctionStaticObj"); 
      SoTest FunctionObj("FunctionObj"); 
    } 
} 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    printf("enter main\n"); 
    function(); 
    function(); 
    getchar();; 
    return 0; 
} 

는 생산 :

이제
C'tor called of CStaticObj  (0x419168) object 
C'tor called of ClassStaticObj (0x419169) object 
enter main 
C'tor called of FunctionStaticObj  (0x419160) object 
C'tor called of FunctionObj  (0x12fe77) object 
C'tor called of FunctionObj  (0x12fe77) object 
C'tor called of FunctionObj  (0x12fe77) object 
C'tor called of FunctionObj  (0x12fe77) object 

질문 (들)

함수의 외부 정적 변수를 선언 사이에 차이가를 함수 내에서 변수 을 정적으로 선언 하시겠습니까?

이들은 완전히 다른 문제입니다. 정적 변수/함수 외부 함수는 컴파일 단위 외부에서 볼 수 없습니다.

함수 내부

정적 변수가 글로벌 데이터에 할당되고 제 occurance 동안 한번만 초기화 (FunctionStaticObj 다른 개체에 모순 주 후에 초기화 된 것을 알 수있다. 또한

하는 선언 차이는 무엇 정적 및 방금 ​​통근 변수를 선언 변수?

다시 고정 수단 밖에 보이지 않는 편집 유닛.

,

extern은 다른 컴파일 단위와 링커에서 관리하지만 여기서는 정의되지 않았 음을 의미하므로 원하는만큼 많은 extern 선언을 만들 수 있지만 하나의 외부 정의는 만들 수 없습니다.

관련 문제