your programing

C의 공유 전역 변수

lovepro 2020. 10. 11. 11:07
반응형

C의 공유 전역 변수


C에서 공유되는 전역 변수를 어떻게 만들 수 있습니까? 헤더 파일에 넣으면 링커가 변수가 이미 정의되어 있다고 불평합니다. 내 C 파일 중 하나에서 변수를 선언하고 extern사용하려는 다른 모든 C 파일의 맨 위에 s 를 수동으로 넣는 유일한 방법 입니까? 이상적이지 않은 것 같습니다.


헤더 파일에 extern. 그리고 c 파일 중 하나의 전역 범위에서 extern.


하나의 헤더 파일 (shared.h)에서 :

extern int this_is_global;

이 전역 기호를 사용하려는 모든 파일에 extern 선언이 포함 된 헤더를 포함합니다.

#include "shared.h"

여러 링커 정의를 방지하려면 컴파일 단위 (예 : shared.cpp)에 전역 기호 선언이 하나만 있어야합니다 .

/* shared.cpp */
#include "shared.h"
int this_is_global;

헤더 파일에서

헤더 파일

#ifndef SHAREFILE_INCLUDED
#define SHAREFILE_INCLUDED
#ifdef  MAIN_FILE
int global;
#else
extern int global;
#endif
#endif

전역에 적용 할 파일이있는 파일에서 다음을 수행하십시오.

#define MAIN_FILE
#include "share.h"

extern 버전이 필요한 다른 파일에서 :

#include "share.h"

헤더 파일에 선언을 넣습니다.

 extern int my_global;

.c 파일 중 하나에서 전역 범위에서 정의합니다.

int my_global;

액세스하려는 모든 .c 파일 my_global에는 externin.


C와 C ++간에 코드를 공유하는 경우 shared.h파일에 다음을 추가해야 합니다.

#ifdef __cplusplus
extern "C" {
#endif

extern int my_global;
/* other extern declarations ... */

#ifdef __cplusplus
}
#endif

헤더 파일이 하나만있는 깔끔한 방법이 있으므로 유지 관리가 더 간단합니다. 전역 변수가있는 헤더에서 각 선언에 키워드 (공통 사용)를 접두사 한 다음 하나의 소스 파일에 다음과 같이 포함하십시오.

#define common
#include "globals.h"
#undef common

및 이와 같은 다른 소스 파일

#define common extern
#include "globals.h"
#undef common

Just make sure you don't initialise any of the variables in the globals.h file or the linker will still complain as an initialised variable is not treated as external even with the extern keyword. The global.h file looks similar to this

#pragma once
common int globala;
common int globalb;
etc.

seems to work for any type of declaration. Don't use the common keyword on #define of course.

참고URL : https://stackoverflow.com/questions/3010647/shared-global-variables-in-c

반응형